简体   繁体   English

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

[英]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但它似乎不起作用

Here is the fiddle这是小提琴

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.除非您实际上要尝试做的事情还有很多,否则将IAsyncResultActionBeginInvoke是非常矫枉过正的。 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.

相关问题 AsyncWaitHandle.WaitOne的详细信息 - Details of AsyncWaitHandle.WaitOne 在非UI线程上调用AsyncWaitHandle.WaitOne时出现NotSupportedException - NotSupportedException when calling AsyncWaitHandle.WaitOne on non-UI Thread AsyncWaitHandle.WaitOne阻止CLR线程吗? 或者它是否创建了I / O完成端口? - Does AsyncWaitHandle.WaitOne block the CLR thread? Or does it create an I/O completion port? 如果侦听服务已关闭,为什么TcpClient.BeginConnect结果的AsyncWaitHandle.WaitOne不返回false? - Why doesn't TcpClient.BeginConnect result's AsyncWaitHandle.WaitOne return false if the listening service is down? IAsyncResult.AsyncWaitHandle.WaitOne()在回调之前完成 - IAsyncResult.AsyncWaitHandle.WaitOne() completes ahead of callback 如何在C#Winforms项目的“ InvokeMember()”之前添加延迟 - How to add a delay before “InvokeMember()” in a C# Winforms project 使用计时器延迟逐行readline方法C# - Using a timer to delay a line by line readline method C# 使用DownloadFile C#开始下载pdf文件之前的延迟 - Delay before starting download of pdf file using DownloadFile C# 在C#中延迟执行SQL查询 - Executing SQL query with delay in C# C#表单由于waitOne而变慢 - C# form slowing down because of waitOne
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM