C# 使用AsyncWaitHandle.WaitOne在C中执行一行之前添加延迟#
我想在C中延迟2秒后执行一个函数# 我尝试了下面的代码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
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次提议的睡眠版本。他最有可能添加延迟只是为了测试异步的东西。他最有可能添加延迟只是为了测试异步的东西。