Created
September 22, 2020 15:24
-
-
Save smailliwcs/1b8c07a2f16bc12bca95dc5a3b4e7c52 to your computer and use it in GitHub Desktop.
Running tasks in STA threads
This file contains 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
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