c# - C# await delay not working
问题描述
I want to pause the program so it does not close. I have a code running in the main thread. Tried this way, but this code instantly skips and the program closes instead of waiting.
How can I make it wait for the WaitMy method to complete?
static void Main(string[] args)
{
//any code here...
Console.WriteLine("Discovery started");
WaitMy();
}
private async static void WaitMy()
{
//await Task.Delay(30 * 1000);
await Task.Run(async () => await Task.Delay(30 * 1000));
}
The application runs with .net 4.5.
解决方案
Change the code to following to make it work:
static async Task Main(string[] args)
{
//any code here...
Console.WriteLine("Discovery started");
await WaitMy();
}
How this works ?
- You need C# 7.1 or later versions
- Now Main method can be declared async and has return type as
Task
for introducingawait
- It will simply let the delay execute asynchronously, but will renter the main context for continuation, which will not exit
Another suggestion would be, you just need await Task.Delay(30 * 1000)
, wrapping inside the Task.Run
is not required here
推荐阅读
- python - 在 numpy 中将科学记数法转换为具有指定精度的浮点数时,set_print_options 失败
- botframework - 默认情况下不支持 Java 8 日期/时间类型:添加模块“com.fasterxml.jackson.datatype:jackson-datatype-jsr310”以启用处理
- .net - 如何在 VB.NET 中为列表属性执行对象初始化程序
- android - 是否可以为某些风味子集定义自定义 android sourceSets?
- performance - 如何计算 jmeter 5.4.1 中所有发送的请求?
- usb - 为什么his3516dv300的D+电压不上拉?
- bash - 如何在调用 kubectl 的函数上启用自动完成子命令
- packer - 使用变量作为其他变量值的一部分
- javascript - 从 JS 连接到 pyzmq websocket
- oracle - Oracle 将函数转换为触发器