Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Created March 24, 2024 09:51
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 atifaziz/6d147cbafb02239551e5807ee55a13c1 to your computer and use it in GitHub Desktop.
Save atifaziz/6d147cbafb02239551e5807ee55a13c1 to your computer and use it in GitHub Desktop.
STA thread as an awaitable task
// Author: Atif Aziz
// License: This code is released by "Author" into the public domain.
using System;
using System.Threading;
using System.Threading.Tasks;
static partial class StaTask
{
public static Task RunAsync(Action action) =>
RunAsync(_ => action(), CancellationToken.None);
public static Task RunAsync(Action<CancellationToken> action, CancellationToken cancellationToken)
{
var completionSource = new TaskCompletionSource();
var thread = new Thread(() =>
{
try
{
action(cancellationToken);
completionSource.SetResult();
}
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken)
{
completionSource.SetCanceled(cancellationToken);
}
catch (Exception ex)
{
completionSource.SetException(ex);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return completionSource.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment