异步等待和并行

13

我对async/await如何并行工作有点困惑,所以我在这里写了一个测试代码。
我尝试发送了6个用列表模拟的任务。
每个任务都将执行3个其他子任务:

你可以复制/粘贴进行测试。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
         static void Main(string[] args)
        {
            //job simulation 
            Func<int, string, Tuple<int, string>> tc = Tuple.Create;
            var input = new List<Tuple<int, string>>{
                  tc( 6000, "task 1" ),
                  tc( 5000, "task 2" ),
                  tc( 1000, "task 3" ),
                  tc( 1000, "task 4" ),
                  tc( 1000, "task 5" ),
                  tc( 1000, "task 6" )
            };

            List<Tuple<int, string>> JobsList = new List<Tuple<int, string>>(input);

            //paralelism atempt
            List<Task> TaskLauncher = new List<Task>();

            Parallel.ForEach<Tuple<int, string>>(JobsList, item =>  JobDispatcher(item.Item1, item.Item2));

            Console.ReadLine();
        }
        public static async Task JobDispatcher(int time , string query)
        {
          List<Task> TList = new List<Task>();
          Task<string> T1 = SubTask1(time, query);
          Task<string> T2 = SubTask2(time, query);
          Task<string> T3 = SubTask3(time, query);
          TList.Add(T1);
          TList.Add(T2);
          TList.Add(T3);
          Console.WriteLine("{0} Launched ", query);

          await Task.WhenAll(TList.ToArray());

        
          Console.WriteLine(T1.Result);
          Console.WriteLine(T2.Result);
          Console.WriteLine(T3.Result);
      
        }


        public static async Task<string> SubTask1(int time, string query)
        {
            //somework
            Thread.Sleep(time);
            return query + "Finshed SubTask1";
        }
        public static async Task<string> SubTask2(int time, string query)
        {
            //somework
            Thread.Sleep(time);
            return query + "Finshed SubTask2";
        }
        public static async Task<string> SubTask3(int time, string query)
         {
             //somework
             Thread.Sleep(time);
             return query + "Finshed SubTask3";
         }


    }
}

最好在启动时我应该阅读:
task 1 launched
task 2 launched
task 3 launched
task 4 launched
task 5 launched
task 6 launched

此时有6*3=18个任务同时运行,但这并不是在这里发生的情况。事情似乎是同步执行的。

结果如下:

Screenshot

写一段可以使用async/await以18个并行线程启动任务和子任务的正确方法是什么?


它并没有同步运行,任务4在任务3之前启动但在任务3之后结束。 - Alexander Derck
请查看这些文章 - Paulo Morgado
@Zwan: async/await是关于异步(不使用线程而实现并发); Parallel是关于并行(使用更多线程实现并发)。这是两种完全不同的并发方式,很少需要同时使用它们。如果您描述一下您实际想要做什么,我们可以建议更合理的解决方案。 - Stephen Cleary
我相信有很多种方法可以实现我所做的事情(所以我尝试使用最新的技术)。基本上,我在主窗体中使用foreach->usercontrol加载,我执行异步usercontrol.methode以避免冻结主窗体。usercontrol.methode本身必须执行3个其他异步usercontrol.methode(sql/acivedirectory/gui等等)。这是主要问题,既不会冻结Mainform也不会冻结usercontrol,并且每个usercontrol都有很多工作要做,因此需要并行处理。虽然Mattew的答案可以胜任,但如果某些方法被封装在usercontrole中,则具有安全性原因。 - Zwan
如何在代码中使用@stephen?哈哈,这对我不起作用。 - Zwan
显示剩余2条评论
1个回答

17

尝试这个示例代码。注意它大约在6秒钟内完成,这表明所有任务都是异步运行的:

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;
            });
        }
    }
}

这里是如何使用任务数组而不是在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);
}

它的反应与我对并行的期望完全一致,但我还不确定为什么我的代码某些部分似乎“阻塞”,而你的代码运行顺畅。稍后会进行调查。无论如何,谢谢,我会在生产代码中尝试这个。 - Zwan
这个答案中的每一个Task.Run调用都不属于这里。底层操作本质上是异步的。在线程池线程中启动异步操作没有任何作用。 - Servy
1
@Servy 我移除了包含 Task.Run() 的版本,但我认为在 worker() 中仍需要 Task.Run()。(之前它有 await Task.Delay(),但为了使其更像 OP 的代码,我已将其替换为 Thread.Sleep(),这意味着现在它需要在一个任务中运行。) - Matthew Watson
是的,它现在可以工作了,列表也可以工作了。我之前进行了复制/粘贴滥用。 - Zwan
1
我来自未来,我尝试了使用WPF的代码(将“Console”替换为“Debug”)。 我注意到“所有任务完成于...”没有显示出来。 解决方案:不要使用RunWorkers().Wait();,改用await RunWorkers();并在Main方法中添加'async'。 - Battle
显示剩余5条评论

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