Async await and parallel

笑着哭i 提交于 2019-12-05 08:13:15

Try this sample code. Note that it completes in around 6 seconds, which shows that all the tasks are run asynchronously:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            // ThreadPool throttling may cause the speed with which
            // the threads are launched to be throttled.
            // You can avoid that by uncommenting the following line,
            // but that is considered bad form:

            // ThreadPool.SetMinThreads(20, 20);

            var sw = Stopwatch.StartNew();
            Console.WriteLine("Waiting for all tasks to complete");

            RunWorkers().Wait();

            Console.WriteLine("All tasks completed in " + sw.Elapsed);
        }

        public static async Task RunWorkers()
        {
            await Task.WhenAll(
                JobDispatcher(6000, "task 1"),
                JobDispatcher(5000, "task 2"),
                JobDispatcher(4000, "task 3"),
                JobDispatcher(3000, "task 4"),
                JobDispatcher(2000, "task 5"),
                JobDispatcher(1000, "task 6")
            );
        }

        public static async Task JobDispatcher(int time, string query)
        {
            var results = await Task.WhenAll(
                worker(time, query + ": Subtask 1"),
                worker(time, query + ": Subtask 2"),
                worker(time, query + ": Subtask 3")
            );

            Console.WriteLine(string.Join("\n", results));
        }

        static async Task<string> worker(int time, string query)
        {
            return await Task.Run(() =>
            {
                Console.WriteLine("Starting worker " + query);
                Thread.Sleep(time);
                Console.WriteLine("Completed worker " + query);
                return query + ": " + time + ", thread id: " + Thread.CurrentThread.ManagedThreadId;
            });
        }
    }
}

Here's how you would use an array of tasks instead, in RunWorkers():

public static async Task RunWorkers()
{
    Task[] tasks = new Task[6];

    for (int i = 0; i < 6; ++i)
        tasks[i] = JobDispatcher(1000 + i*1000, "task " + i);

    await Task.WhenAll(tasks);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!