C# 异步等待和并行
我对async/await如何并行工作有点困惑,所以我在这里编写了一个测试代码: 我尝试发送6个我用列表模拟的任务。 每个任务将执行另外3个子任务 您可以复制/粘贴以进行测试C# 异步等待和并行,c#,async-await,parallel.foreach,C#,Async Await,Parallel.foreach,我对async/await如何并行工作有点困惑,所以我在这里编写了一个测试代码: 我尝试发送6个我用列表模拟的任务。 每个任务将执行另外3个子任务 您可以复制/粘贴以进行测试 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleAppl
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";
}
}
}
然后在这一点上,让所有运行6*3=18线程的任务同时运行
但这里发生的事情似乎并不是同步的
结果如下:
使用async/await编写可以作为18个并行线程启动任务和子任务的正确方法是什么?试试下面的示例代码。请注意,它大约在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;
});
}
}
}
它不是同步运行的,任务4在任务3之前启动,但在任务3之后完成。首先,它应该先在控制台中编写,因为我稍后在函数中等待子任务。请看一下。@Zwan:
async
/await
是关于异步的(没有线程的并发)<代码>并行是关于并行性(通过使用更多线程实现并发)。这些是完全不同的并发方法,您很少同时需要这两种方法。也许,如果你描述一下你实际上想做什么,我们可以建议一个更合理的解决方案?构建线程的有趣方法我可以在静态异步任务工作者(int-time,string-query)方法中添加3个子任务吗?它的反应与我对Parallel的期望完全一样。我还不知道我的代码的某些部分看起来“阻塞”的确切原因当你的代码运行顺利时。稍后将进行调查。无论如何,感谢将在生产代码中尝试此方法。感谢使用第一篇文章中的值时间。你的代码是6秒,当我的12秒证明开始时,有些东西运行不平行…每一个任务。运行调用此答案不属于这里。底层操作本质上是异步的。通过在线程池线程中启动异步操作,您将一事无成。@Servy我删除了具有Task.Run()
的版本,但我相信它仍然需要worker()
中的Task.Run()
。(它以前有wait Task.Delay()
,但为了使它更像OP的代码,我将其替换为Thread.Sleep()
,这意味着现在它需要在任务中运行。)
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;
});
}
}
}
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);
}