我想在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");
但它似乎不起作用
以下是fiddle
我只想在向用户显示一些警告消息后导航到另一个页面
答案 0 :(得分:0)
除非你实际上要做的事情还要多得多,否则弄乱IAsyncResult
,Action
和BeginInvoke
对于你想要完成的事情来说是一个巨大的过度杀伤力。您所需要做的就是:
Thread.Sleep(1000);
// call your funcction
答案 1 :(得分:0)
如前所述,您可以使用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());
}
输出:
延迟记录
完成
1000