如何为该代码添加任务并行性?我已经在几个地方添加了,但是它没有按预期运行。
class Program
{
static void Main(string[] args)
{
Task.Run(() =>PizzaTask());
}
static async void PizzaTask()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int totalPizza = 10;
Console.WriteLine($"Started preparing {totalPizza} pizza");
for (var x = 1; x <= totalPizza; x++)
{
//Task.Run(() => MakePizza(x));
await MakePizza(x);
}
stopwatch.Stop();
Console.WriteLine($"Finished preparing {totalPizza} pizza");
Console.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds);
}
static async Task MakePizza(int n)
{
PreparePizza(n);
await BakePizza(n);
}
static void PreparePizza(int n)
{
Console.WriteLine("Start preparing pizza " + n);
Thread.Sleep(5000);// synchronous
Console.WriteLine("Finished preparing pizza " + n);
}
static async Task BakePizza(int n)
{
Console.WriteLine("Start baking pizza " + n);
await Task.Delay(15000); // asynchronous
//Thread.Sleep(15000); // synchronous
Console.WriteLine("Finished baking pizza " + n);
}
}
之前的工作版本在BakePizza中,我设置为异步等待。但是,如果我为PizzaTask()设置了异步等待,它将无法正常工作。
我已经更改了代码,以使其通过var tasks = Enumerable.Range(0, totalPizza).Select(i => MakePizza(i));
使用并行循环来异步处理>
下面的代码并行调用MakePizza
,而不是通过for (var x = 1; x <= totalPizza; x++)
{
//Task.Run(() => MakePizza(x));
await MakePizza(x);
}
使用Task.Delay
而不是Thread.Sleep
以确保当前线程未被阻止。
async void
更改为aysnc Task
。 async+void
组合可能会使系统崩溃,通常只应在UI端事件处理程序上使用。ConfigureAwait(false)
返回任何可用线程,而不是强制上下文返回调用者线程。 更新的代码:
public class Program { public static void Main() { PizzaTask().GetAwaiter().GetResult(); } static async Task PizzaTask() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); int totalPizza = 10; Console.WriteLine("Started preparing " + totalPizza + " pizza"); var tasks = Enumerable.Range(0, totalPizza).Select(i => MakePizza(i)); await Task.WhenAll(tasks).ConfigureAwait(false); stopwatch.Stop(); Console.WriteLine("Finished preparing " + totalPizza + " pizza"); Console.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds); } static async Task MakePizza(int n) { await PreparePizza(n).ConfigureAwait(false); await BakePizza(n).ConfigureAwait(false); } static async Task PreparePizza(int n) { Console.WriteLine("Start preparing pizza " + n); await Task.Delay(5000); //Thread.Sleep(5000);// synchronous Console.WriteLine("Finished preparing pizza " + n); } static async Task BakePizza(int n) { Console.WriteLine("Start baking pizza " + n); await Task.Delay(15000); // asynchronous //Thread.Sleep(15000); // synchronous Console.WriteLine("Finished baking pizza " + n); } }
您可以在dotnetfiddle中检查代码的输出-https://dotnetfiddle.net/HepavC