Created
March 24, 2024 09:51
-
-
Save atifaziz/6d147cbafb02239551e5807ee55a13c1 to your computer and use it in GitHub Desktop.
STA thread as an awaitable task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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