I am trying to set the apartment state on a task but see no option in doing this. Is there a way to do this using a Task?
for (int i = 0; i < zom.Count; i++) { Task t = Task.Factory.StartNew(zom[i].Process); t.Wait(); }
When StartNew
fails you just do it yourself:
public static Task<T> StartSTATask<T>(Func<T> func) { var tcs = new TaskCompletionSource<T>(); Thread thread = new Thread(() => { try { tcs.SetResult(func()); } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; }
(You can create one for Task
that will look almost identical, or add overloads for some of the various options that StartNew
has.)
An overload of Servy's answer to start a void Task
public static Task StartSTATask(Action func) { var tcs = new TaskCompletionSource<object>(); var thread = new Thread(() => { try { func(); tcs.SetResult(null); } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With