[英]using AsyncWaitHandle.WaitOne to add delay before executing a line in C#
I want to execute a function after some 2 seconds delay in C#我想在 C# 中延迟大约 2 秒后执行一个函数
I tried the below code我试过下面的代码
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");
But it doesn't seem to work但它似乎不起作用
I just want to navigate to a different page after showing some alert message to user我只想在向用户显示一些警报消息后导航到不同的页面
Unless there's a lot more to what you're actually trying to do, messing around with IAsyncResult
, Action
, and BeginInvoke
is massive overkill.除非您实际上要尝试做的事情还有很多,否则将IAsyncResult
、 Action
和BeginInvoke
是非常矫枉过正的。 All you need to do is:您需要做的就是:
Thread.Sleep(1000);
// call your funcction
As already proposed, you can use the System.Threading.Thread.Sleep method to delay your call:正如已经提出的,您可以使用System.Threading.Thread.Sleep方法来延迟您的调用:
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());
}
Output:输出:
Delayed logging延迟记录
Completed完全的
1000 1000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.