Monthly Archives: May 2015

Running .NET Tasks in STA Threads

Task StartSTATask(Action action)
{
    TaskCompletionSource<object> source = new TaskCompletionSource<object>();
    Thread thread = new Thread(() =>
        {
            try
            {
                action();
                source.SetResult(null);
            }
            catch (Exception ex)
            {
                source.SetException(ex);
            }
        });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return source.Task;
}

Task<TResult> StartSTATask<TResult>(Func<TResult> function)
{
    TaskCompletionSource<TResult> source = new TaskCompletionSource<TResult>();
    Thread thread = new Thread(() =>
        {
            try
            {
                source.SetResult(function());
            }
            catch (Exception ex)
            {
                source.SetException(ex);
            }
        });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return source.Task;
}