简体   繁体   English

如何保证异步方法继续在另一个线程上运行?

[英]How to guarantee that async method continuation runs on another thread?

Does ConfigureAwait(false) guarantee that continuation runs on a different thread or only signals that it's not compulsory to run on the same thread? ConfigureAwait(false)保证继续在不同的线程上运行还是仅表示不强制在同一线程上运行?

Is there any way to provide that guarantee? 有什么办法可以提供保证?

I need to test context flow across threads. 我需要测试跨线程的上下文流。

Using ConfigureAwait(false) tells the awaiter not to resume on the captured context and so the SynchronizationContext is ignored. 使用ConfigureAwait(false)告诉等待者不要在捕获的上下文上继续,因此SynchronizationContext被忽略。 That means that the continuation would be scheduled by the default TaskScheduler that uses ThreadPool threads. 这意味着继续将由使用ThreadPool线程的默认TaskScheduler调度。

If the original thread was a ThreadPool thread, the continuation may run on the same thread, otherwise your guaranteed it's a different thread. 如果原始线程是ThreadPool线程,则该延续可以在同一线程上运行,否则可以保证它是不同的线程。

You can start your test using a dedicated thread without a SynchronizationContext (or with ConfigureAwait(false) ) to make sure the threads are different before and after the async operation. 您可以使用不带SynchronizationContext的专用线程(或使用ConfigureAwait(false) )启动测试,以确保async操作之前和之后的线程不同。

There's below scenario which ConfigureAwait(false) doesn't run a new context. 在以下情况下, ConfigureAwait(false)不运行新上下文。

Task task2Seconds = Wait2Seconds();
Task task5Seconds = Wait5Seconds();

await task5Seconds;
await task2Seconds.ConfigureAwait(false);

The first await doesn't have that ConfigureAwait(false) but it takes longer than the second await who has that configure but be ready to resume in advance. 第一次await没有那个ConfigureAwait(false)但是它比第二次await拥有那个配置但准备好提前恢复的时间更长。 So the second will resume on the same context. 因此,第二个将在相同的上下文中恢复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM