Asynchronously wait for Task to complete with timeout in C#

5
(1)

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.

 

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?