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:
- Use an AutoResetEvent (or
ManualResetEvent) combined with an
annonymus method using
.WaitOne(x). - 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?
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.)