Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用AsyncWaitHandle.WaitOne在C中执行一行之前添加延迟#_C# - Fatal编程技术网

C# 使用AsyncWaitHandle.WaitOne在C中执行一行之前添加延迟#

C# 使用AsyncWaitHandle.WaitOne在C中执行一行之前添加延迟#,c#,C#,我想在C中延迟2秒后执行一个函数# 我尝试了下面的代码 IAsyncResult result; Action action = () => { //I want to call my function here after 1 second delay Console.WriteLine("Delayed logging"); }; result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.W

我想在C中延迟2秒后执行一个函数#

我尝试了下面的代码

IAsyncResult result;
Action action = () =>
{
    //I want to call my function here after 1 second delay
    Console.WriteLine("Delayed logging");
};

result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(500000))
    Console.WriteLine("Completed");
else
    Console.WriteLine("done");
但它似乎不起作用

这是你的电话号码


在向用户显示一些警告消息后,我只想导航到另一个页面,除非您实际要做的事情还有很多,在
IAsyncResult
Action
、以及
BeginInvoke
中乱搞都是大肆渲染。您需要做的只是:

Thread.Sleep(1000);
// call your funcction

除非你真正想做的事情还有很多,否则在
IAsyncResult
Action
、和
BeginInvoke
上乱搞简直是大材小用。您需要做的只是:

Thread.Sleep(1000);
// call your funcction

如前所述,您可以使用该方法延迟呼叫:

public static void Main()
{

    IAsyncResult result;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    Action action = () =>
    {
        Thread.Sleep(1000);
        //I want to call my function here after 1 second delay
        Console.WriteLine("Delayed logging");
    };

    result = action.BeginInvoke(null, null);
    if (result.AsyncWaitHandle.WaitOne(500000))
        Console.WriteLine("Completed");
    else
        Console.WriteLine("done");

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds.ToString());
}
输出:

延迟日志记录
已完成
一千


如前所述,您可以使用该方法延迟呼叫:

public static void Main()
{

    IAsyncResult result;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    Action action = () =>
    {
        Thread.Sleep(1000);
        //I want to call my function here after 1 second delay
        Console.WriteLine("Delayed logging");
    };

    result = action.BeginInvoke(null, null);
    if (result.AsyncWaitHandle.WaitOne(500000))
        Console.WriteLine("Completed");
    else
        Console.WriteLine("done");

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds.ToString());
}
输出:

延迟日志记录
已完成
一千


正如@Ðаn提到的,您可能应该
Thread.Sleep(1000)这是带有时间测量的。对于已经提出了3次的睡眠版本。正如@Ðаn所提到的,您可能应该
Thread.sleep(1000)这是带有时间测量的。已经有3次提议的睡眠版本。他最有可能添加延迟只是为了测试异步的东西。他最有可能添加延迟只是为了测试异步的东西。