与C#中的顺序执行相比,多线程花费的时间更多 [英] Multithreading takes more time than Sequential Execution in C#

查看:472
本文介绍了与C#中的顺序执行相比,多线程花费的时间更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在while循环中使用多线程,

I am using Multithreading in my while loop , as

while(reader.read())
{
 string Number= (reader["Num"] != DBNull.Value) ? reader["Num"].ToString() : string.Empty;
  threadarray[RowCount] = new Thread(() =>
  {

  object ID= (from r in Datasetds.Tables[0].AsEnumerable()
                                            where r.Field<string>("Num") == Number
                                            select r.Field<int>("ID")).First<int>();


 });

                threadarray[RowCount].Start();
                RowCount++;
}

但是按顺序执行,对于200个读取器,仅需0.4 s 但是使用线程需要1.1秒钟...这是一个示例,但是当我在执行多个数据库操作的线程中使用多行代码执行它时,我遇到了同样的问题.

But with sequential execution ,for 200 readers it just takes 0.4 s but with threading it takes 1.1 sec... This is an example but i have same problem when i execute it with number of lines of code in threading with multiple database operations.

顺序执行需要10秒的线程处理时间,而且需要更多时间...

for sequential it takes 10 sec for threading it takes more...

有人可以建议我吗?

谢谢...

推荐答案

线程并非总是更快,而且在许多情况下可能会更慢(例如此处所示的情况).有很多原因,但最重要的两个是

Threading is not always quicker and in many cases can be slower (such as the case seen here). There are plenty of reasons why but the two most significant are

  • 创建线程是相对昂贵的OS操作
  • 上下文切换(CPU停止在一个线程上工作并开始在另一个线程上工作)再次是相对昂贵的操作

创建200个线程将花费相当长的时间(使用默认堆栈大小,这将单独为堆栈分配200MB的内存),并且除非您有一台具有200个内核的计算机,否则操作系统也将需要花费相当多的时间.在这些线程之间进行时间上下文切换.

Creating 200 threads will take a fair amount of time (with the default stack size this will allocate 200MB of memory for stacks alone), and unless you have a machine with 200 cores the OS will also need to spend a fair amount of time context switching between those threads too.

最终结果是,机器花费在创建线程以及在线程之间切换所花费的时间仅仅超过了机器花费在执行任何工作上的时间.如果减少使用的线程数,则可能会看到性能提高.对于您的计算机所具有的每个核心,请尝试从1个线程开始.

The end result is that the time that the machine spends creating threads and switching between them simply outstrips the amount of time that the machine spends doing any work. You may see a performance improvement if you reduce the number of threads being used. Try starting with 1 thread for each core that your machine has.

多线程(其中线程多于内核)通常仅在CPU闲置等待事情发生的情况下才有用(例如磁盘IO或网络通信).这里不是这种情况.

Multithreading where you have more threads than cores is generally only useful in scenarios where the CPU is hanging around waiting for things to happen (like disk IO or network communication). This isn't the case here.

这篇关于与C#中的顺序执行相比,多线程花费的时间更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆