可以异步方法有昂贵的code之前的第一个“等待”?第一个、昂贵、方法、code

2023-09-04 00:40:14 作者:星星坠入梦境

难道是坏有昂贵的code在异步方法的开始,之前的第一个伺机被称为?如果这code被包裹着 TaskEx.Run 呢?

 公共异步任务美孚()
{
    //做一些初步昂贵的东西。
    // ...

    //为异步方法与计谋第一个电话。
    等待DoSomethingAsync;
}
 

解决方案

由于里德说,这真的取决于上下文。在code已经在运行的部分的一点 - 但根据上下文,它可能最终被一个线程池线程,而不是一些关键的运行

而不是使用 Task.Run ,我会使用 TaskEx.Yield

 公共异步任务美孚()
{
    等待TaskEx.Yield();
    //做昂贵的东西
}
 

据我所知,这基本上立即返回给调用者,但允许被调度通俗易懂的异步方法的其余部分的一种方式。如果你在像Windows窗体UI线程,紧随就是在做这个没有意义,你会回来的UI线程(与运行昂贵的code有) - 但它将使意义,如果你这一点,在当前线程不应该被阻止,但延续的另一个线程上运行。

VSCode必备插件 C C 开发

Is it bad to have expensive code at the start of an async method, before the first await is called? Should this code be wrapped with a TaskEx.Run instead?

public async Task Foo()
{
    // Do some initial expensive stuff.
    // ...

    // First call to an async method with await.
    await DoSomethingAsync;
}

解决方案

As Reed says, it really depends on the context. The code has to run at some point - but depending on the context, it may end up being run on a thread pool thread instead of some critical one.

Rather than using Task.Run, I'd use TaskEx.Yield:

public async Task Foo()
{
    await TaskEx.Yield();
    // Do expensive stuff
}

As far as I'm aware, that's basically a way of immediately returning to the caller, but allowing the rest of the async method to be scheduled straightaway. If you're in something like a Windows Forms UI thread, there's no point in doing this as you'll be back to the UI thread (and running expensive code there) immediately - but it would make sense if you're in a context where the current thread shouldn't be blocked, but continuations are run on another thread.

 
精彩推荐
图片推荐