1

I would like to emulate this code:

Task t = Task.Factory.StartNew(...)
t.Wait()

According to this question Tasks cannot set apartment state. Apartment state can be set using Threads but I need the Wait functionality in Tasks. Is there a way to emulate the Wait() function using Threads?

Community
  • 1
  • 1
Luke101
  • 63,072
  • 85
  • 231
  • 359
  • Are you trying to achieve the blocking until the Task is complete, or do you need to interact with async/await/TPL? – Erick T May 23 '13 at 19:49
  • Are you just starting one task in another thread and immediately blocking until it completes? If so, then just call it synchronously. – mbeckish May 23 '13 at 19:52
  • @mbeckish That's not an option if you're not on an STA thread and the method needs to be run on an STA thread. – Servy May 23 '13 at 19:54
  • You may user (Auto/Manual)ResetEvent. Pass instance into task and set event on task complete. Outside task, after start, user WaitOne or similar method – Uzzy May 23 '13 at 19:59
  • @Uzzy 1) He doesn't have a task. He has a `Thread`. He's asking how to wait on a thread. 2) Why would you do all of that when there's a single method that already exists that does *exactly* what he needs? – Servy May 23 '13 at 20:04

1 Answers1

5

Thread.Join will block the current thread until another thread completes.

Oh, and for the record, the statement Tasks cannot set apartment state isn't correct. Perhaps StartNew will never create a task that represents work in an STA thread, but some other method could create a Task that represented work in an STA thread. For example, this one does:

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

Servy
  • 202,030
  • 26
  • 332
  • 449
  • This looks nice. How would I convert this method to use an Action instead? – Luke101 May 23 '13 at 20:53
  • @Luke101 You Change the signature as appropriate and just set a dummy value in the TCS. It's pretty much just copy-paste. – Servy May 23 '13 at 20:54