简体   繁体   English

将并行 ForEach 转换为 PLINQ 以处理任务列表

[英]Converting Parallel ForEach into PLINQ to process list of Tasks

I am trying to process as many messages into a server fast as possible.我正在尝试尽快将尽可能多的消息处理到服务器中。 I currently have this bit of code and to load 50000 messages to a MessagingServer it takes around 5 minutes.我目前有这段代码,将 50000 条消息加载到 MessagingServer 大约需要 5 分钟。 This is a list of tasks that have server name, queuename and the message to place on the queue.这是具有服务器名称、队列名称和要放置在队列中的消息的任务列表。

  taskList.Add(new Task(() => PlaceMessageOnQueue(server, queueName, message)));

I want to convert this to PLINQ as hopes to make this even faster.我想将其转换为 PLINQ,以使其更快。

_= Parallel.ForEach(task, new ParallelOptions()
{
MaxDegreeOfParallelism = Environment.ProcessorCount; //I have 4 Cpu's
},t => {
 t.Start();
 t.Wait();
Console.WriteLine(t.Status)
});

What I have so far but this isn't starting the tasks到目前为止我所拥有的但这并没有开始任务

var results = task.
.AsParallel()
.AsOrdered()
.WithDegreeofParallelism(Environment.ProcessorCount)
.ToList();

You have typos in your code that prevent it from compiling, but after fixing those, it runs as expected.您的代码中有拼写错误导致无法编译,但在修复这些拼写错误后,它会按预期运行。 Each task runs with expected concurrency, and when all tasks have completed, the code exits.每个任务都以预期的并发性运行,当所有任务都完成后,代码退出。 Here's a console program demonstrating this:这是一个控制台程序,演示了这一点:

class Program
{
    static void Main(string[] args)
    {
        var taskList = new List<Task>();

        for (int i = 0; i < 10; i++)
            taskList.Add(new Task(() => PlaceMessageOnQueue("FOO", "BAR", $"Message {i}")));

        var _ = Parallel.ForEach(taskList, new ParallelOptions()
        {
            MaxDegreeOfParallelism = Environment.ProcessorCount //I have 4 Cpu's
        },t =>
        {
            t.Start();
            t.Wait();
            Console.WriteLine(t.Status);
        });
    }
    static void PlaceMessageOnQueue(string server, string queue, string message)
    {
        Console.WriteLine($"Starting {server}/{queue}/{message}");
        Thread.Sleep(1000);
        Console.WriteLine($"Finished {server}/{queue}/{message}");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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