In Winforms/WPF the following code works:
var id = Thread.CurrentThread.ManagedThreadId;
await DoAsync();
var @equals = id == Thread.CurrentThread.ManagedThreadId; //TRUE
I know that await DoAsync().ConfigureAwait(false)
will resume in another thread.
However, how can this WinForms/WPF behavior can be accomplished in the, say, Console App? In the console app, the above condition will return FALSE, regardless if I use ConfigureAwait(true/false)
. My app is not a console, it's just the same behavior.
I have several classes that implements IMyInterface
with a method Task<IInterface> MyMethod()
and in my starting point I need to start in a STA thread, so I create an STA thread like this
public static Task<TResult> Start<TResult>(Func<TResult> action, ApartmentState state, CancellationToken cancellation)
{
var completion = new TaskCompletionSource<TResult>();
var thread = new Thread(() =>
{
try
{
completion.SetResult(action());
}
catch (Exception ex)
{
completion.SetException(ex);
}
});
thread.IsBackground = true;
thread.SetApartmentState(state);
if (cancellation.IsCancellationRequested)
completion.SetCanceled();
else
thread.Start();
return completion.Task;
}
So I must ensure that in every class that implements IMyInterface
it resumes to the STA thread created in the beginning.
How can one accomplish that?