C#多线程ApartmentState.STA

需要设置子线程 ApartmentState 为 STA 模式,但 Task 又不能直接设置 ApartmentState,因此需要用 Thread 来封装一下。

C#多线程ApartmentState.STA
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;
});
C#多线程ApartmentState.STA
上一篇:C# Memcache集群原理、客户端配置详细解析


下一篇:day-5