Task.Yield 方法

定义

创建异步产生当前上下文的等待任务。Creates an awaitable task that asynchronously yields back to the current context when awaited.

public:
 static System::Runtime::CompilerServices::YieldAwaitable Yield();
public static System.Runtime.CompilerServices.YieldAwaitable Yield ();
static member Yield : unit -> System.Runtime.CompilerServices.YieldAwaitable
Public Shared Function Yield () As YieldAwaitable

返回

YieldAwaitable

等待时,上下文将异步转换回等待时的当前上下文。A context that, when awaited, will asynchronously transition back into the current context at the time of the await. 如果当前 SynchronizationContext 不为 null,则将其视为当前上下文。If the current SynchronizationContext is non-null, it is treated as the current context. 否则,与当前执行任务关联的任务计划程序将视为当前上下文。Otherwise, the task scheduler that is associated with the currently executing task is treated as the current context.

注解

可以 await Task.Yield(); 在异步方法中使用来强制异步完成方法。You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously. 如果当前同步上下文 (SynchronizationContext 对象) ,则这会将该方法的其余执行内容发布回该上下文。If there is a current synchronization context (SynchronizationContext object), this will post the remainder of the method's execution back to that context. 但是,上下文将决定如何将此工作的优先级设置为相对于可能挂起的其他工作。However, the context will decide how to prioritize this work relative to other work that may be pending. 大多数 UI 环境中的 UI 线程上出现的同步上下文通常会将发布到上下文的工作的优先级设置为高于输入和呈现工作的优先级。The synchronization context that is present on a UI thread in most UI environments will often prioritize work posted to the context higher than input and rendering work. 出于此原因,请不要依赖 await Task.Yield(); 于保持 UI 的响应能力。For this reason, do not rely on await Task.Yield(); to keep a UI responsive. 有关详细信息,请参阅通过 .NET 并行编程中的 System.threading.tasks.task.continuewith 启用的有用抽象 博客。For more information, see the entry Useful Abstractions Enabled with ContinueWith in the Parallel Programming with .NET blog.

适用于