简体   繁体   中英

C# No performance gain with Task?

I used Task like below but there is no performance gain. I checked my method which executes in 0-1 seconds but with Task(30 Tasks), it takes 5-12 seconds. Can anyone guide if I have done any mistake. I want to run 30 parallel and expect 30 done in max 2 seconds.

Here is my code:

Task[] tasks = new Task[30];
for (int p = 0; p <= dstable.Tables[0].Rows.Count - 1; p++)
{
    MethodParameters newParameter = new MethodParameters();
    newParameter.Name = dstable.Tables[0].Rows[p]["Name"].ToString();

    tasks[p] = Task.Factory.StartNew(() => ParseUri(newParameter));
    Application.DoEvents();
}
try
{
    Task.WaitAll(tasks);
    //Console.Write("task completed");
}
catch (AggregateException ae)
{
    throw ae.Flatten();
}

There are some major problems in your thinking.

  1. does your PC have 30 Cores, so that every core can exactly takes one task? I don't think so
  2. starting a seperate thread also takes some time.
  3. with every concurrent thread more overhead is generated.
  4. Can your problem be solved faster by starting more threads? This is only the case, when all threads do different tasks, like reading from disk, quering a database, computing something, etc.. 10 threads that do all "high-performance" tasks on the cpu, won't give an boost, quite contrary to, because every thread needs to clean up his mess, before he can give some cpu time to the next thread, and that one needs to clean up his mess too.

Check this link out http://msdn.microsoft.com/en-us/library/ms810437.aspx

You can use the TPL http://msdn.microsoft.com/en-us/library/dd460717.aspx

they try to guaranty the maximum effect from parallel threads. Also I recommend this book http://www.amazon.com/The-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916

When you really want to solve your problem in under 2 seconds, buy more CPU power ;)

I think you may have missing the main point of using thread.

  • Creating many threads may lead to more complexity by increasing OS over-head. (Context switching)
  • Also it will be much harder to manage your execution of code and harder to find and fix bugs if there is any.

Usage of thread may give you advantage when there is

  • Task need to be perform simultaneously
  • Building responsive UI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM