Set ApartmentState on a mission

I try to set the state of the apartment on a task, but I do not see 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(); } 
+32
c #
May 23 '13 at 17:42
source share
3 answers

When StartNew crashes, 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 it for Task , which will look almost identical, or add overloads for some of the various options that StartNew has.)

+73
May 23 '13 at 19:56
source share

Servy overload response to run 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; } 
+9
Feb 11 '16 at 22:46
source share

You can, for example, do a new task as follows:

  try { Task reportTask = Task.Factory.StartNew( () => { Report report = new Report(this._manager); report.ExporterPDF(); } , CancellationToken.None , TaskCreationOptions.None , TaskScheduler.FromCurrentSynchronizationContext() ); reportTask.Wait(); } catch (AggregateException ex) { foreach(var exception in ex.InnerExceptions) { throw ex.InnerException; } } 
+8
Jun 20 '13 at 14:29
source share



All Articles