执行异步同步功能

执行异步同步功能

本文介绍了执行异步同步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了很多搜索关于这个话题,我在这个网站关于这个话题读取大多数的帖子在这里,但我仍然困惑,我需要一个简单的答案。这里是我的情况:

我有一个既定的WinForm应用程序,我不能让这一切异步。我现在被迫使用是所有写为异步函数外部库。

在我的应用我有

  ///<总结>
///此功能,我不能将其更改为异步
///< /总结>
公共无效MySyncFunction()
{
    //这个函数是我在我的应用程序地步,我必须调用
    //其他异步功能,但我不能在功能本身更改为异步    尝试
    {
        //我需要调用MyAsyncDriverFunction(),就好像它是一个同步功能
        //我需要的驱动函数执行完成和处理code遵循之前返回
        //我还需要能够捕获任何异常
        MyAsyncDriverFunction();        在code的//其余的等待上面的函数返回
    }
    赶上(例外EXP)
    {
        //需要能够处理引发的异常
        //从这里MyAsyncDriverFunction。
    }
}公共静态异步任务<&IEnumerable的LT;串GT;> MyAsyncDriverFunction()
{
    尝试
    {
        VAR strCollection =等待AsyncExternalLibraryFunction1();
        VAR strCollection2 =等待AsyncExternalLibraryFunction2();        返回strCollection;
    }
    赶上(例外EXP)
    {
        //需要能够捕捉异常,并重新抛出给调用者函数
    }
}

由于在code概括,我需要能够:


  • 我无法将MySyncFunction更改为异步

  • 调用在同步方式,它必须等待它完成所有的工作,我处理code遵循
  • 前的MyAsyncDriverFunction
  • 能够处理这两种功能异常(从我到目前为止,这是棘手的阅读?)

  • 我需要使用标准的API一个简单的方法,我不能使用任何第三方库(即使我想)


解决方案

That's because there isn't a "straight-forward" answer.

The only proper solution is to make MySyncFunction asynchronous. Period. All other solutions are hacks, and there is no hack that works perfectly in all scenarios.

I go into full details in my recent MSDN article on brownfield async development, but here's the gist:

You can block with Wait() or Result. As others have noted, you can easily cause a deadlock, but this can work if the asynchronous code never resumes on its captured context.

You can push the work to a thread pool thread and then block. However, this assumes that the asynchronous work is capable of being pushed to some other arbitrary thread and that it can resume on other threads, thus possibly introducing multithreading.

You can push the work to a thread pool thread that executes a "main loop" - e.g., a dispatcher or my own AsyncContext type. This assumes the asynchronous work is capable of being pushed to another thread but removes any concerns about multithreading.

You can install a nested message loop on the main thread. This will execute the asynchronous code on the calling thread, but also introduces reentrancy, which is extremely difficult to reason about correctly.

In short, there is no one answer. Every single approach is a hack that works for different kinds of asynchronous code.

这篇关于执行异步同步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:17