Alternative to Thread.Sleep that block

萝らか妹 提交于 2019-12-11 12:54:32

问题


I am looking for an alternative to calling Thread.Sleep which does not block the thread but instead returns the thread back into the thread pool. Does such a thing exist?


回答1:


Use Task.Delay

await Task.Delay(delay);



回答2:


If the thread is returning to the pool, then it isn't going to do any more work in the method in question. Make the next bit of the method a separate method, and create a Timer that calls it.




回答3:


You can use also a Timer for example:

using System.Timers;

private void Main()
{
    Timer t = new Timer();
    t.Interval = 5000; // 5 seconds
    t.AutoReset = false;
    t.Elapsed += new SleepDone(TimerElapsed);
    t.Start();
}

private void SleepDone(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("HERE WHAT COME AFTER SLEEP");
}


来源:https://stackoverflow.com/questions/20001169/alternative-to-thread-sleep-that-block

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