C# Parallel Vs. Threaded code performance

前端 未结 4 1136
耶瑟儿~
耶瑟儿~ 2021-02-14 03:19

I\'ve been testing the performance of System.Threading.Parallel vs a Threading and I\'m surprised to see Parallel taking longer to finish tasks than threading. I\'m sure it\'s d

4条回答
  •  醉酒成梦
    2021-02-14 04:15

    I think I can answer your question. First of all, you didn't write how many cores your system has. if you are running a dual-core, only 4 thread will work using the Parallel.For while you are working with 10 threads in your Thread example. More threads will work better as the task you are running (Printing + Short sleep) is a very short task for threading and the thread overhead is very large compared to the task, I'm almost sure that if you write the same code without threads it will work faster.

    Both your methods works pretty much the same but if you create all the threads in advance you save a lot as the Parallel.For uses the Task pool which adds some move overhead.

提交回复
热议问题