Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 stops it, the therad is timed out.

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

Suggestions?

like image 493
Jaster Avatar asked Apr 08 '26 09:04

Jaster


1 Answers

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.)

like image 171
Jon Skeet Avatar answered Apr 10 '26 00:04

Jon Skeet