问题描述
据我所知,Task.Yield
在方法的开头会强制调用者继续,如果它没有等待该方法.同时 Task.Run
和 ConfigureAwait(false)
两者 在新的线程池线程上运行任务,如果调用者没有等待该方法,这将再次强制调用者继续.
As I understand it, Task.Yield
at the beginning of a method will force the caller to continue if it is not awaiting the method. Meanwhile Task.Run
and ConfigureAwait(false)
both run a Task on a new thread pool thread, which again will force the caller to continue if it is not awaiting the method.
我无法理解 Task.Yield
和运行一个新的线程池线程之间的区别,因为在它返回调用者之后,它将继续执行该方法的其余部分,即本质上是一样的.
I can't understand the difference between Task.Yield
and running a new thread pool thread, since right after it returns to the caller, it will continue executing the rest of the method, which is essentially the same thing.
这篇 帖子表明 Yield
和 Task.Factory.StartNew
(实际上只是 Task.Run
的旧版本)可以互换使用,这让我感到困惑.
This post suggests that Yield
and Task.Factory.StartNew
(which is really just the old version of Task.Run
) can be used interchangeably, which seems confusing to me.
推荐答案
Task.Yield
不是 Task.Run
的替代品,它没有什么可替代的使用 Task.ConfigureAwait
.
Task.Yield
is not a replacement for Task.Run
and it has nothing to do with Task.ConfigureAwait
.
Task.Yield
- 生成一个等待对象,在检查完成后立即完成.ConfigureAwait(false)
- 从忽略捕获的SynchronizationContext
的任务中生成可等待对象.Task.Run
- 在ThreadPool
线程上执行委托.
Task.Yield
- Generates an awaitable that completes just after it is checked for completion.ConfigureAwait(false)
- Generates an awaitable from a task that disregards the capturedSynchronizationContext
.Task.Run
- Executes a delegate on aThreadPool
thread.
Task.Yield
与 ConfigureAwait
的不同之处在于它本身是一个可等待对象,而不是另一个可等待对象(即 Task).另一个区别是
Task.Yield
确实在捕获的上下文中继续.
Task.Yield
is different than ConfigureAwait
in that it is an awaitable all by itself, and not a configurable wrapper of another awaitable (i.e. the Task
). Another difference is that Task.Yield
does continue on the captured context.
Task.Run
与两者不同,因为它只需要一个委托并在 ThreadPool
上运行它,您可以将它与 ConfigureAwait(false) 或不.
Task.Run
is different then both as it just takes a delegate and runs it on the ThreadPool
, you can use it with ConfigureAwait(false)
or without.
Task.Yield
应该用于强制异步点,而不是替代 Task.Run
.当在 async 方法中到达 await 时,它会检查任务(或其他可等待的)是否已经完成,如果是,则继续同步.Task.Yield
可防止这种情况发生,因此对测试很有用.
Task.Yield
should be used to force an asynchronous point, not as a replacement to Task.Run
. When await is reached in an async method it checks whether the task (or other awaitable) already completed and if so it continues on synchronously. Task.Yield
prevents that from happening so it's useful for testing.
另一种用法是在 UI 方法中,您不想占用单个 UI 线程,您插入一个异步点,其余的安排在稍后执行.
Another usage is in UI methods, where you don't want to be hogging the single UI thread, you insert an asynchronous point and the rest is scheduled to be executed in a later time.
这篇关于Task.Yield、Task.Run 和 ConfigureAwait(false) 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!