我对此主题进行了大量搜索,并且阅读了本网站上有关此主题的大部分帖子,但是我仍然感到困惑,我需要一个直接的答案。这是我的情况:
我有一个已建立的 Winform 应用程序,但无法使其全部“异步”。我现在被迫使用一个全部编写为异步函数的外部库。
在我的应用程序中我有
/// <summary>
/// This function I can't change it to an 'async'
/// </summary>
public void MySyncFunction()
{
//This function is my point in my application where I have to call the
//other 'async' functions but I can't change the function itself to 'async'
try
{
//I need to call the MyAsyncDriverFunction() as if it is a synchronous function
//I need the driver function to finish execution and return before processing the code that follows it
//I also need to be able to catch any exceptions
MyAsyncDriverFunction();
//Rest of the code have to wait for the above function to return
}
catch (Exception exp)
{
//Need to be able to handle the exception thrown
//from the MyAsyncDriverFunction here.
}
}
public static async Task<IEnumerable<string>> MyAsyncDriverFunction()
{
try
{
var strCollection = await AsyncExternalLibraryFunction1();
var strCollection2 = await AsyncExternalLibraryFunction2();
return strCollection;
}
catch (Exception exp)
{
//Need to be able to catch an exception and re-throw it to the caller function
}
}
正如代码中所述,我需要能够:
- 我无法将 MySyncFunction 更改为异步
- 以同步方式调用“MyAsyncDriverFunction”,它必须等待它完成所有工作,然后才能处理后面的代码
- 能够处理两个函数中的异常(从我到目前为止读到的内容来看,这很棘手?)
- 我需要一种使用标准 API 的简单方法,我不能使用任何第三方库(即使我想)
但是我仍然很困惑,我需要一个直接的答案。
那是因为没有“直接”的答案.
The only正确的解决方案是使MySyncFunction
异步。时期。所有其他解决方案都是黑客,并且没有一种黑客可以在所有场景下完美工作.
我详细介绍了我最近关于棕地异步开发的 MSDN 文章 https://msdn.microsoft.com/en-us/magazine/mt238404.aspx,但要点如下:
您可以阻止Wait()
or Result
。正如其他人所指出的,您很容易导致死锁,但如果异步代码永远不会在其捕获的上下文上恢复,则这可以起作用。
您可以将工作推送到线程池线程,然后阻塞。但是,这假设异步工作能够被推送到其他任意线程and它可以继续other线程,因此可能引入多线程。
您可以将工作推送到执行“主循环”的线程池线程 - 例如调度程序或我自己的AsyncContext
类型。这假设异步工作能够被推送到另一个线程,但消除了对多线程的任何担忧。
您可以在主线程上安装嵌套消息循环。这将在调用线程上执行异步代码,但也会引入重入性,即极其很难正确推理。
简而言之,没有一个答案。每一种方法都是一种适用于不同类型的异步代码的技巧。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)