为什么该程序不会等待x秒?

时间:2018-12-08 22:38:17

标签: c#

所以我来自python,正在尝试将我的python程序之一转换为c#程序。由于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));


        }
    }

}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-2)

异步的性质意味着它与其他事件同时发生,例如@LasseVågsætherKarlsen说,您实质上是派遣了一个小工人去做,而主程序仍在继续。

如果您希望主线程等待,则可以使用类似的

Thread.Sleep(5000);

这将导致您的主线程在继续下一行之前暂停(以毫秒为单位)。

希望这会有所帮助!

相关问题