.NET应用程序多线程

3

我有一颗多核心的CPU,但我写的.NET应用程序只使用其中一个核心。当此选项可用时,如何使其使用多个核心。

4个回答

7

4
你可以尝试使用JaredPar提到的Microsoft Parallel Extensions to .NET Framework 3.5,或自己创建一个多线程版本的程序。下面我将给出一个更具体的示例,演示如何将现有程序中的“for循环”轻松转换为使用Parallel Extension中的System.Threading.Parallel。例如,对于检查0到maxnum之间每个素数的for循环:
System.Threading.Parallel.For(0, maxNum + 1, x => IsPrime(x));  

很容易,是吧?

我还进行了一项有关 System.Parallel 性能改进的简单基准测试。我希望 SO 同行不介意我在这里发布我的博客链接:这里

alt text


0

将耗时的任务分派到多个线程中。

使用ThreadPool是实现多线程的建议方式。

以下是MSDN提供的ThreadPool示例:

using System;
using System.Threading;
public class Example {
    public static void Main() {

        // Queue the task.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task. 
    static void ThreadProc(Object stateInfo) {

        // No state object was passed to QueueUserWorkItem, so  
        // stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}

0

@JaredPar 给出了一个优秀的答案。然而,在某些情况下,重写代码以实现多线程可能并不值得。多线程代码更加复杂,并且增加了一整套额外的错误类型需要解决。

然而,在桌面应用程序的简单情况下,有时候值得将双核机器的第二个核心空闲下来,这样操作系统就可以利用它来做其他应用程序的屏幕重绘、运行病毒扫描等任务。

这可能不是你想听到的答案,但在某些情况下,这是一种务实的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接