I\'m looking for an efficient way to throw a timeout exception if a synchronous method takes too long to execute. I\'ve seen some samples but nothing that quite does what I
If you have a Task
called task
, you can do this:
var delay = Task.Delay(TimeSpan.FromSeconds(3));
var timeoutTask = Task.WhenAny(task, delay);
If timeoutTask.Result
ends up being task
, then it didn't timeout. Otherwise, it's delay
and it did timeout.
I don't know if this is going to behave identically to what you have implemented, but it's the built-in way to do this.