c# - 为什么这个程序不会等待 x 秒?
问题描述
所以我来自 python,我正在尝试将我的一个 python 程序转换为 ac# 程序。由于 c# 对我来说是全新的,我已经遇到了一个简单的问题,在 python 中看起来像这样:
import time
time.sleep(5)
但在 c# 中我似乎无法让它工作。有人能指出为什么在打印“等待 5 秒”之前它不会等待 5 秒吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
Console.WriteLine("Hello World!");
Program.wait_for_seconds(5);
Console.WriteLine("Waited for 5 seconds");
Console.ReadKey();
// Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!
}
public static async void wait_for_seconds(Double args)
{
await Task.Delay(TimeSpan.FromSeconds(args));
}
}
}
解决方案
需要使用 await 关键字调用异步函数。如果您不使用 await 关键字调用异步函数,则意味着您不关心进程何时以及如何完成,因此程序不会在函数调用时停止(被阻塞)。
采用
await Program.wait_for_seconds(5);
看看有什么不同。
PS:请注意,您需要将 Main 方法更改为
static async Task Main(string[] args)
为了能够在 main 中使用 await 关键字。
另请注意,您需要为此更改启用 C# 7.1 功能。
Program.wait_for_seconds(5);
另一种方法是同步调用方法
Program.wait_for_seconds(5).RunSynchronously();
或者
Program.wait_for_seconds(5).Wait();
但是不建议在同步方法中调用异步方法,也不能这样做。
推荐阅读
- python - 是否可以使用 pywin32 将拖动命令发送到后台的非活动窗口?
- sql - 合并任何为空的 SQL 查询结果
- mysql - 我注意到查询生成器在我的第一个子查询中添加了额外的括号 '(' & ')'!MYSQL 8 错误
- python - Python2 到 Python3 的迁移导致我依赖的 django-earthdistance 包出现问题
- java - AWS CodeCommit 中的 Maven 问题
- php - 重命名表名时,实际上是从 Mysql 中删除表 - 使用 PHP
- python - 无法获取拆分 python 的访问令牌
- php - Laravel SQLSTATE[23000] 无法删除或更新父行:外键约束失败
- xslt - XSLT关于按多个元素分组并进行相应总结的问题
- .htaccess - 如果只有特定的 URL 匹配,则 URL 重定向 htaccess