C#等待一段时间而不会阻塞 [英] c# wait for a while without blocking

查看:652
本文介绍了C#等待一段时间而不会阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的方法来等待约500毫秒,然后检查一些标志已更改。如何在没有挡住了我的应用程序的其余部分完成这个?

I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?

推荐答案

Thread.sleep代码(500)将迫使当前线程等待500毫秒。它的工作原理,但它不是你想要的,如果你的整个应用程序在一个线程中运行。

Thread.Sleep(500) will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.

在这种情况下,你需要使用一个定时器,就像这样:

In that case, you'll want to use a Timer, like so:

using System.Timers;

void Main()
{
    Timer t = new Timer();
    t.Interval = 500; //In milliseconds here
    t.AutoReset = true; //Stops it from repeating
    t.Elapsed += new ElapsedEventHandler(TimerElapsed);
    t.Start();
}

void TimerElapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Hello, world!");
}

您还可以设置自动复位为假(或不设置的话),如果你希望计时器重演。

You can also set AutoReset to false (or not set it at all) if you want the timer to repeat itself.

这篇关于C#等待一段时间而不会阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆