简体   繁体   中英

Parallel using tasks

I am currently creating an engine that will spin 10 new threads up that will do diffrent work. But i have found that my solution dose not run in Parallel.

public async Task Start(Func<string, Task> action)
{
   for (var i = 1; i <= config.threads; i++)
    {
        consumers.Add(getActionTask(action));
    }

    await Task.WhenAll(consumers);
}

private Task getActionTask(Func<string, Task> action)
{
    return Task.Run(async () =>
    {
        // Do something that returns a string
        String data = "Some string here";
        await action(data);
    }
}

Lets say i run 2 threads, and based on data will the first thread do a Task.Delay(TimeSpan.FromSeconds(30)); The second thread will print "Hello" on a loop.

It will never get the print loop before the Delay is over, what is wrong with my implementation?

The Task.WhenAll doesn't say that the tasks will run in parallel. It creates a Task that would be completed once all the tasks you pass as an argument to the WhenAll method would be completed.

If you want your code to run in parallel, you should make use of the Parallel class ForEach method.

Update

One important note as Scott pointed out below in his comment is that the functions in the Parallel class do not work with async methods. If you want to use async methods with it you must use TPL Dataflow instead.

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