ApartmentState.STA
作者:互联网
需要设置子线程 ApartmentState 为 STA 模式,但 Task 又不能直接设置 ApartmentState,因此需要用 Thread 来封装一下。
using System.Threading; using System.Threading.Tasks; public static Task<T> StartSTATask<T>(Func<T> func) { var tcs = new TaskCompletionSource<T>(); var thread = new Thread(() => { try { tcs.SetResult(func()); } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; } var task = StartSTATask<WebBrowser>(() => { WebBrowser browser = new WebBrowser(); return browser; });
标签:Task,STA,tcs,var,new,ApartmentState 来源: https://www.cnblogs.com/soundcode/p/11027054.html