C#多线程 [英] C# Multi-Threading

查看:161
本文介绍了C#多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个需要运行特定功能最多100,000次的应用程序.名为Calculate()的函数中包含一个运行100,000次的迭代循环.


当前执行此操作需要104秒.我希望能够做到这一点,而不是将其设置为100,000次迭代,将其设置为4,000,然后分别在25个线程上运行Calculate().

Good day all,

I have an application that needs to run a specific function up to 100,000 times. A function called Calculate() has within it an iteration loop that runs 100,000 times.


Currently doing this takes 104 seconds. What I would like to be able to do it rather than have it set at 100,000 iterations, have it set at 4,000 and run Calculate() seperately on 25 threads.

public void Calculate()
        {
            int iterate = 0;
            
            
            while (iterate < 4000)
            {
                    
                //Do Work

                iterate++;
            }
            
        }



谁能用我上面的例子解释我该怎么做?

非常感谢您的时间,

Mike.



Can anyone explain using my example above how I can do this?

Your time is very much appreciated,

Mike.

推荐答案

似乎可以用for循环替换该函数.如果是这样,您可以尝试在.Net 4中使用新的Parallel类.您不必自己拆分任务,因为我相信它包括线程自己的负载平衡".
It looks like you could replace that function with a for loop. If so you could try using the new Parallel class in .Net 4. You won''t have to split the tasks up yourself as I believe it includes it''s own ''load balancing'' for threads.


就像Tony所说的那样,如果可以使用.NET 4,则可以使用新的Parallel东西.我自己开始使用它,几乎将双核处理器的运行时间减少了一半. 此处是一篇很好的文章.考虑您的代码示例:
Like Tony said, if you can use .NET 4, you could use the new Parallel stuff. I started using that myself, almost reduces the elapsed time by half on my dual core processor. Here is a good article how to do it. Considering your code example:
public void Calculate()
        {
            System.Threading.Tasks.Parallel.For(0, 100000,
                i =>
                {
                    //You have access to i here
                    //Do work.
                }
            );
        }


希望有帮助,
AnılYıldız.


Hope that helps,
Anıl Yıldız.


这篇关于C#多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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