Reputation: 8254
let's say we have some simple code like this :
private static void Main()
{
Console.WriteLine("Main thread {0}\n", Thread.CurrentThread.ManagedThreadId);
Action asyncCaller1 = () => LongPerfomingTask(5);
Action asyncCaller2 = () => LongPerfomingTask(3);
var asyncResult1 = asyncCaller1.BeginInvoke(null, null);
var asyncResult2 = asyncCaller2.BeginInvoke(null, null);
asyncResult1.AsyncWaitHandle.WaitOne();
asyncResult2.AsyncWaitHandle.WaitOne();
Console.WriteLine("Done");
}
private static void LongPerfomringTask(int seconds)
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("Thread {0} finished execution", Thread.CurrentThread.ManagedThreadId);
}
Delegate.BeginInvoke() does not create a thread, It's executing code in a caller's thread when it is in idle state, right?So, why the output of this sample application is like this :
Main thread 1
Thread 4 finished execution
Thread 3 finished execution
Done
Upvotes: 1
Views: 7726
Reputation: 8007
@taras.roshko: Here's a resource to boost your understanding of ThreadPool: Chapter on Threading
Upvotes: 0
Reputation: 1503449
No, Delegate.BeginInvoke
uses the thread pool. Always. There's no concept of "executing in the caller's thread when it's idle" unless you're thinking of adding tasks to a UI message queue... were you getting confused with Control.BeginInvoke
/ Dispatcher.BeginInvoke
?
In this case you've got a console app - there's no message pumping going on to start with.
Upvotes: 6