开发者

Find no way to make Async call in parallel (multi-threads)

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 开发者_JAVA技巧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 ThreadPool ramping up gradually, basically. The idea is that it's relatively expensive to create (and then keep) threads, and the ThreadPool is 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.


The first time you have spawned many threads that do the job in parallel. The second time you have used thread-pool, which has a limited number of threads. As Jon noted you can use a property to define the minimum thread number.

But, why do you need that to make async call from your parallel threads?
This will not improve your performance at all, as your work is already done in parallel plus and you are making another split (using thread pool), which will introduce more latencies due to thread context switch. There is no need to do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜