Reputation: 4399
Can the result of an async operation be returned to the thread that initiated it (ie.AsyncCallback
invoked in the original thread)?
Here's an example
void Main(string[] args)
{
Func<bool> action = () =>
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Running");
return true;
};
AsyncCallback onComplete = (r) =>
{
bool result = action.EndInvoke(r);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Completed");
};
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Main");
IAsyncResult iar = action.BeginInvoke(onComplete, null);
}
Its output is something like:
5: Main
6: Running
6: Completed
What I'd like to achieve is the onComplete
callback executing in the main thread (eg. Completed and Main will have the same thread id printed in this example)
(I know this can be achieved with a BackgroundWorker
ie. it's RunWorkerCompleted
event is fired in the original thread and therefore the return value of the function invoked in the background thread can be returned to the original thread)
Upvotes: 2
Views: 419
Reputation: 1062650
This is largely a question for the SynchronizationContext
and TaskScheduler
implementations that you choose to use. In the case of many UI frameworks (winforms, WPF, etc), then yes: if you start work on the UI thread, the callback can happen on the UI thread - but this does not apply in the general case, where a ThreadPool
thread is more likely to win. Ultimately, you can't simply force work back to a particular thread, unless that thread is by design checking some queue of work, and dequeing / executing packets of work as they arrive (which is exactly what UI frameworks do).
Upvotes: 5