问题描述
我要放2操作之间的延迟,而不忙于线程
I want to put a delay between 2 operations without keeping busy the thread
workA();
Thread.Sleep(1000);
workB();
线程必须workA后退出,一些延迟后执行workB(也许在一个新的线程)。
The thread must exit after workA and execute workB (maybe in a new thread) after some delay.
我不知道是否有可能对这种伪code一些equevalent
I wonder if it's possible some equevalent of this pseudocode
workA();
Thread.BeginSleep(1000, workB); // callback
编辑我的计划是在.NET 2.0
editMy program is in .NET 2.0
编辑2:System.Timers.Timer.Elapsed活动将在1000毫秒引发事件。我不知道,如果计时器线程将忙于为1000毫秒。 (所以我不获得线程经济)
edit 2 :System.Timers.Timer.Elapsed event will raise the event after 1000 ms. I dont know if the timer thread will be busy for 1000 ms. (so I dont gain thread economy)
推荐答案
你的意思是:
Task.Delay(1000).ContinueWith(t => workB());
另外,创建一个定时器
手动。
请注意,这看起来prettier在异步
code:
Note this looks prettier in async
code:
async Task Foo() {
workA();
await Task.Delay(1000);
workB();
}
编辑:用你的.NET 2.0的更新,你就必须建立自己的定时器
有回调。有一个的NuGet包 System.Threading.Tasks ,带来了任务
API到.NET 3.5,但它并不会去2.0,和b:我不认为它包括 Task.Delay
。
edit: with your .NET 2.0 update, you would have to setup your own Timer
with callback. There is a nuget package System.Threading.Tasks that brings the Task
API down to .NET 3.5, but a: it doesn't go to 2.0, and b: I don't think it includes Task.Delay
.
这篇关于异步Thread.sleep代码()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!