【发布时间】:2021-08-02 11:45:28
【问题描述】:
我正在使用下面的代码,想测试一下并行编程,但是有一些问题。
using System;
using System.Threading.Tasks;
namespace DemoParallelApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("*** Main Method Start ***");
Operation();
Console.WriteLine("*** Main Method End ***");
}
static void Operation()
{
Console.WriteLine("*** Operation Method Start ***");
var task1 = Delay(5000);
Console.WriteLine("*** Operation Method End ***");
}
static async Task<int> Delay(int ms)
{
Console.WriteLine($"Start {ms}(ms) Delay");
await Task.Delay(ms);
Console.WriteLine($"End {ms}(ms) Delay");
return ms;
}
}
}
结果是这样的:
*** Main Method Start ***
*** Operation Method Start
*** Start 5000(ms) Delay
*** Operation Method End ***
*** Main Method End ***
但我觉得应该是这样的:
*** Main Method Start ***
*** Operation Method Start ***
Start 5000(ms) Delay
*** Operation Method End ***
*** Main Method End ***
End 5000(ms) Delay
这有什么问题?
【问题讨论】:
-
并行还是异步?
-
async 也是并行的,不是吗?
-
使用 await 你正在等待 Task.Delay(ms) 结束
-
那我该怎么做延迟呢?
标签: c# asynchronous .net-core parallel-processing console-application