创建异步产生当前上下文的等待任务。等待时,上下文将异步转换回等待时的当前上下文。 如果当前 SynchronizationContext 不为 null,则将其视为当前上下文。 否则,与当前执行任务关联的任务计划程序将视为当前上下文。
//Console
internal class Program
{
static void Main(string[] args)
{
Test();
Console.ReadLine();
}
static async void Test()
{
Console.WriteLine($"Before线程ID:{Thread.CurrentThread.ManagedThreadId}");
await Task.Yield();
Console.WriteLine($"After线程ID:{Thread.CurrentThread.ManagedThreadId}");
Task.Delay(1000).Wait(); ;
}
}
//WPF
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Test();
}
static async void Test()
{
Console.WriteLine($"Before线程ID:{Thread.CurrentThread.ManagedThreadId}");
await Task.Yield();
Console.WriteLine($"After线程ID:{Thread.CurrentThread.ManagedThreadId}");
Task.Delay(1000).Wait(); ;
}
}
注意点:
1.Task.Yield 会主动把控制权返回给调用方
2.Task.Yield 后面的工作的执行线程要看SynchronizationContext是不是为Null,如果为空 则会有task scheduler来调度执行,在控制台和在WPF/WInform上打印线程ID的结果是不同的
这个用途看网上的文章大意是说为了不阻塞调用方 具体可以看一下文章:
终于明白了 C# 中 Task.Yield 的用途 - dudu - 博客园 (cnblogs.com)
Task.Yield 方法 (System.Threading.Tasks) | Microsoft Learn
await Task.Yield()和await Task.CompletedTask有什么不同 - PowerCoder - 博客园 (cnblogs.com)