Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smailliwcs/1b8c07a2f16bc12bca95dc5a3b4e7c52 to your computer and use it in GitHub Desktop.
Save smailliwcs/1b8c07a2f16bc12bca95dc5a3b4e7c52 to your computer and use it in GitHub Desktop.
Running tasks in STA threads
using System;
using System.Threading;
using System.Threading.Tasks;
public static class STATask
{
public static Task Start(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;
}
public static Task<TResult> Start<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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment