Monitoring a synchronous method for timeout

后端 未结 4 1283
孤街浪徒
孤街浪徒 2020-12-30 04:20

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

4条回答
  •  攒了一身酷
    2020-12-30 04:44

    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.

提交回复
热议问题