Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ApartmentState on a Task

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(); } 
like image 880
Luke101 Avatar asked May 23 '13 17:05

Luke101


2 Answers

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.)

like image 153
Servy Avatar answered Sep 19 '22 18:09

Servy


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; } 
like image 40
David Avatar answered Sep 23 '22 18:09

David