首页 > 解决方案 > 为什么这个程序不会等待 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));


        }
    }

}

标签: c#

解决方案


需要使用 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();

但是不建议在同步方法中调用异步方法,也不能这样做。


推荐阅读