Asynchronous task timeout?

There is a very common task that I face again. I already solved this a couple of times, but now I'm looking for a more " elegant " one - can you deliver some kind of input?

Situation:
I have a method that I would like to run "sem async". In other words: Run it and wait for the set time x. If the method is not completed by then ("timed out"), I want to continue my code with some cleanup procedures.

Solutions so far:

  • Use AutoResetEvent (or ManualResetEvent) in combination with the annonymus method using .WaitOne (x).
  • Use Thread / BackgroundWorker in conjunction with a timer. If the timer removes its handler before the thread stops it, therad is disabled.

Both experts work fine, but I think 4.0 is better.

Suggestions?

+3
source share
1 answer

Does Task.Wait(Timeout)the parallel task library do what you want? (You can combine this with cancel tokens to cancel the task after the timeout expires.)

+6
source

Source: https://habr.com/ru/post/1777410/


All Articles