Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

.net - Asynchronous Thread.Sleep()

I want to put a delay between 2 operations without keeping busy the thread

 workA();
 Thread.Sleep(1000);
 workB();

The thread must exit after workA and execute workB (maybe in a new thread) after some delay.

I wonder if it's possible some equevalent of this pseudocode

workA();
Thread.BeginSleep(1000, workB); // callback

edit My program is in .NET 2.0

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you mean:

Task.Delay(1000).ContinueWith(t => workB());

Alternatively, create a Timer manually.

Note this looks prettier in async code:

async Task Foo() {
    workA();
    await Task.Delay(1000);
    workB();
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...