开发者

Async Task Timeout?

There is a very common task I face again. I have already solved this a couple of times, but now I am looking for a more "elegant" way - can you deliver some input?

Situation:

I have a Method which I would like to run "semi async". In other words: Start it and wait a given time x. If the method is not finished by then ("timed out"), I want to continue my code with some cleanup procedures.

Solutions so far:

  1. Use an AutoResetEvent (or ManualResetEvent) combined with an annonymus method using .WaitOne(x).

  2. Use a Thread/BackgroundWorker combined with a Timer. If the timer hits its handler before the thread stop开发者_开发知识库s it, the therad is timed out.

Both appraochs work fine but I imagine there is a better way with 4.0.

Suggestions?


Does Task.Wait(Timeout) from the Task Parallel Library do what you want? (You may wish to combine this with cancellation tokens to cancel the task after the timeout occurs.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜