需要设置子线程 ApartmentState 为 STA 模式,但 Task 又不能直接设置 ApartmentState,因此需要用 Thread 来封装一下。
代码语言:javascript复制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;
});