您现在的位置是:主页 > news > 手机网站运营/上海营销公司

手机网站运营/上海营销公司

admin2025/5/3 19:12:19news

简介手机网站运营,上海营销公司,如何做旅游网站的供应商,有什么网站可以做宣传一般来说,await会捕获当前同步上下文SynchronizationContext.Current,如果同步上下文为null,则继续捕获TaskScheduler.Current。await之后的代码会恢复到捕获的上下文继续执行。但是如果你的异步操作执行的比较早,例如在Applicati…

手机网站运营,上海营销公司,如何做旅游网站的供应商,有什么网站可以做宣传一般来说,await会捕获当前同步上下文SynchronizationContext.Current,如果同步上下文为null,则继续捕获TaskScheduler.Current。await之后的代码会恢复到捕获的上下文继续执行。但是如果你的异步操作执行的比较早,例如在Applicati…

一般来说,await会捕获当前同步上下文SynchronizationContext.Current,如果同步上下文为null,则继续捕获TaskScheduler.Current。await之后的代码会恢复到捕获的上下文继续执行。但是如果你的异步操作执行的比较早,例如在Application.Run(new Form1())之前执行:

	static class Program{/// <summary>///  The main entry point for the application./// </summary>[STAThread]static void Main(){Application.SetHighDpiMode(HighDpiMode.SystemAware);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);var s=SynchronizationContext.Current;//此时为nullvar s2=TaskScheduler.Current;GetAsync();Application.Run(new Form1());}static async Task<bool> GetAsync(){MessageBox.Show($"thread id {Thread.CurrentThread.ManagedThreadId}");bool flag = await Task.Factory.StartNew<bool>(() =>{Thread.Sleep(1000);return true;});MessageBox.Show($"thread id {Thread.CurrentThread.ManagedThreadId}");return flag;}}

这时候就会看到两次的thread id不是同一个值。因为调用GetAsync()之前没有捕获到SynchronizationContext.Current,只有TaskScheduler.Current,await之后的操作就执行到了TaskScheduler.Current上。解决方法也比较简单,Winform是是在第一个控件被创建的时候设置SynchronizationContext.Current的,所以在GetAsync之前旧先把Form1给new出来:

Application.SetCompatibleTextRenderingDefault(false);
var f=new Form1();
GetAsync();
Application.Run(f);
  1. Asynchronous Programming - Async from the Start
  2. I thought await continued on the same thread as the caller, but it seems not to