Asynchronously wait for Task<T> to complete with timeout in C#
Here is the original question: How to add timeout in Async Task in c#?
Example for Asynchronously wait for Task<T> to complete with timeout in C#. If you are working with an async task then you may be required to add some timeout for a particular task. Here I give an example that shows how to add timeout functionality to your Async task or Async method in C#.
int timeout = 2000; //2 Second timeout var task = YourAsyncMethodOrTask(); //without await keyword if (await Task.WhenAny(task, Task.Delay(timeout)) == task) { // task completed within timeout ... } else { // Add timeout logic here ... }
You can add your timeout logic into else part.
Hope this will helps.