当您对await进行Task时,默认情况下,延续在同一线程上运行。您真正需要的唯一时间是您是否在UI线程上,并且延续也需要在UI线程上运行。

您可以使用ConfigureAwait对此进行控制,例如:

await SomeMethodAsync().ConfigureAwait(false);

...这对于从不需要在那里运行的UI线程分担工作很有用。 (但是请参阅下面的斯蒂芬·克雷里的评论。)

现在考虑以下代码:
try
{
    await ThrowingMethodAsync().ConfigureAwait(false);
}
catch (Exception e)
{
    // Which thread am I on now?
}

那呢?
try
{
    await NonThrowingMethodAsync().ConfigureAwait(false);

    // At this point we *may* be on a different thread

    await ThrowingMethodAsync().ConfigureAwait(false);
}
catch (Exception e)
{
    // Which thread am I on now?
}

最佳答案

异常将发生在没有异常的情况下继续发生的任何线程上。

try
{
    await ThrowingMethodAsync().ConfigureAwait(false);
}
catch (Exception e)
{
    // Which thread am I on now?
    //A: Likely a Thread pool thread unless ThrowingMethodAsync threw
    //   synchronously (without a await happening first) then it would be on the same
    //   thread that the function was called on.
}

try
{
    await NonThrowingMethodAsync().ConfigureAwait(false);

    // At this point we *may* be on a different thread

    await ThrowingMethodAsync().ConfigureAwait(false);
}
catch (Exception e)
{
    // Which thread am I on now?
    //A: Likely a Thread pool thread unless ThrowingMethodAsync threw
    //   synchronously (without a await happening first) then it would be on the same
    //   thread that the function was called on.
}

为了更加清楚:
private async Task ThrowingMethodAsync()
{
    throw new Exception(); //This would cause the exception to be thrown and observed on
                           // the calling thread even if ConfigureAwait(false) was used.
                           // on the calling method.
}

private async Task ThrowingMethodAsync2()
{
    await Task.Delay(1000);
    throw new Exception(); //This would cause the exception to be thrown on the SynchronizationContext
                           // thread (UI) but observed on the thread determined by ConfigureAwait
                           // being true or false in the calling method.
}

private async Task ThrowingMethodAsync3()
{
    await Task.Delay(1000).ConfigureAwait(false);
    throw new Exception(); //This would cause the exception to be thrown on the threadpool
                           // thread but observed on the thread determined by ConfigureAwait
                           // being true or false in the calling method.
}

关于c# - ConfigureAwait : On which thread is the exception handled?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35136801/

10-13 06:22