简体   繁体   中英

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. 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.

_= 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}");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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