At first I have thread waiting example and it works perfect. It’s job is ask 100 threads wait 3 seconds and then make output:
for (int i = 0; i < 100; ++i)
{
int index = i;
Thread t = new Thread(() =>
{
Caller c = new Caller();
c.DoWaitCall();
}) { IsBackground = true };
t.Start();
}
the Caller::DoWaitCall() looks like:
public void DoWaitCall()
{
Thread.Sleep(3000);
Console.WriteLine("done");
}
In this case, all threads wait 3 seconds and give output message almost in same time.
But when I try to use Async callback to do the Console.WriteLine:
public void DoWaitCall()
{
MyDel del = () => { Thread.Sleep(3000); };
del.BeginInvoke(CallBack, del);
}
private void CallBack(IAsyncResult r)
{
Console.WriteLine("done");
}
Each thread wait for different time, and make their output one-by-one slowly.
Is there any good way to achieve async callback in parallel?
The effect you’re seeing is the
ThreadPoolramping up gradually, basically. The idea is that it’s relatively expensive to create (and then keep) threads, and theThreadPoolis designed for short-running tasks. So if it receives a bunch of tasks in a short space of time, it makes sense to batch them up, only starting new threads when it spots that there are still tasks waiting a little bit later.You can force it to keep a minimum number of threads around using
ThreadPool.SetMinThreads. For real systems you shouldn’t normally need to do this, but it makes sense for a demo or something similar.