Wait for a while without blocking main thread

丶灬走出姿态 提交于 2019-11-26 16:58:32

问题


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?


回答1:


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
    t.AutoReset = false; // Stops it from repeating
    t.Elapsed += new ElapsedEventHandler(TimerElapsed);
    t.Start();
}

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

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




回答2:


You can use await Task.Delay(500); without blocking the thread like Sleep does, and with a lot less code than a Timer.




回答3:


I don't really understand the question.

If you want to block before checking, use Thread.Sleep(500);

If you want to check asynchronously every x seconds, you can use a Timer to execute a handler every x milliseconds.

This will not block your current thread.




回答4:


It the method in question is executing on a different thread than the rest of your application, then do the following:

Thread.Sleep(500);



回答5:


System.Threading.Thread.Sleep(500);

Update

This won't block the rest of your application, just the thread that is running your method.




回答6:


Using a timer should do the trick

if you need to use a thread then here is an example

void Main()
{
    System.Threading.Thread check= new System.Threading.Thread(CheckMethod);
    check.Start();
}

private void CheckMethod()
{
     //Code
     Thread.Sleep(500);
}



回答7:


Asynchron Task:

 var task = new Task (() => function_test()); task.Start();

public void function_test() { `Wait for 5000 miliseconds`   Task.Delay(5000);` }


来源:https://stackoverflow.com/questions/8496275/wait-for-a-while-without-blocking-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!