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