3

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?

Jaster
  • 8,255
  • 3
  • 34
  • 60
  • possible duplicate of [Asynchronously wait for Task to complete with timeout](http://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout) – i3arnon Sep 08 '14 at 22:42

1 Answers1

6

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194