---
title: "Reactive Extensions (Rx) - Part 8 - Timeouts - Muhammad Rehan Saeed"
description: "Should you use Reactive Extensions (Rx) to do timeouts in .NET? It turns out it's better to use CancellationTokenSource in the Task Parallel Library (TPL)."
canonical_url: "https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/"
last_updated: "2017-01-02T00:00:00+00:00"
meta:
  author: "Muhammad Rehan Saeed"
  keywords: ".NET,Base Class Library,BCL,Reactive Extensions,Rx,Task Parallel Library,TPL"
  "og:description": "Should you use Reactive Extensions (Rx) to do timeouts in .NET? It turns out it's better to use CancellationTokenSource in the Task Parallel Library (TPL)."
  "og:image": "https://rehansaeed.com/_og/s/o_b2cc180be96121ec.png"
  "og:image:alt": "Reactive Extensions (Rx) - Part 8 - Timeouts - Muhammad Rehan Saeed"
  "og:image:height": "630"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Reactive Extensions (Rx) - Part 8 - Timeouts"
  "twitter:image": "https://rehansaeed.com/_og/s/o_b2cc180be96121ec.png"
  "twitter:image:alt": "Reactive Extensions (Rx) - Part 8 - Timeouts - Muhammad Rehan Saeed"
---

> Index of every page on this site: [llms.txt](https://rehansaeed.com/llms.txt)

# [Reactive Extensions (Rx) - Part 8 - Timeouts](https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/)

Posted 2 January 2017 - **1 min read**

![Reactive Extensions](https://rehansaeed.com/_ipx/f_png&s_2560x1440/images/hero/Reactive-Extensions-1366x768.png)

1. [Reactive Extensions (Rx) - Replacing C# Events](https://rehansaeed.com/reactive-extensions-part1-replacing-events/)
2. [Reactive Extensions (Rx) - Wrapping C# Events](https://rehansaeed.com/reactive-extensions-part2-wrapping-events/)
3. [Reactive Extensions (Rx) - Naming Conventions](https://rehansaeed.com/reactive-extensions-part3-naming-conventions/)
4. [Reactive Extensions (Rx) - Replacing Timers](https://rehansaeed.com/reactive-extensions-part4-replacing-timers/)
5. [Reactive Extensions (Rx) - Awaiting Observables](https://rehansaeed.com/reactive-extensions-part5-awaiting-observables/)
6. [Reactive Extensions (Rx) - Task ToObservable](https://rehansaeed.com/reactive-extensions-part6-task-toobservable/)
7. [Reactive Extensions (Rx) - Sample Events](https://rehansaeed.com/reactive-extensions-part7-sample-events/)
8. [Reactive Extensions (Rx) - Timeouts](https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/)

In [part six](https://rehansaeed.com/reactive-extensions-part6-task-toobservable/) of this series of blog posts I talked about using Reactive Extensions for adding timeout logic to asynchronous tasks. Something like this:

```cs
public async Task<string> WaitForFirstResultWithTimeOut()
{
    Task<string> task = this.DownloadTheInternet();
 
    return await task
        .ToObservable()
        .Timeout(TimeSpan.FromMilliseconds(1000))
        .FirstAsync();
}
```

Last week I was working on a project and wanted to add a Timeout to my task but since it was an ASP.NET MVC project, I had no references to Reactive Extensions. After some thought I discovered another possible method of performing a timeout which may help in certain circumstances.

```cs
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000)))
{
    try
    {
        return await this.DownloadTheInternet(cancellationTokenSource.Token);
    }
    catch (OperationCanceledException exception)
    {
        Console.WriteLine("Timed Out");
    }
}
```

I'm using an overload on `CancellationTokenSource` which takes a timeout value. Then passing the `CancellationToken` to `DownloadTheInternet`. This method should be periodically checking the `CancellationToken` to see if it has been cancelled and if so, throw an `OperationCanceledException`. In this example you'd probably use `HttpClient` which handles this for you if you give it the CancellationToken.

The main reason why this method is better is that the task is actually being cancelled and stopped from doing any more work. In my above reactive extensions example, the task continues doing work but it's result is just ignored.

## Web Mentions

[What's this?](https://en.wikipedia.org/wiki/Webmention)

### 0 Linked

### 0 Replies

## GitHub Comments

### 1 Comment

[Comment on GitHub](https://github.com/RehanSaeed/rehansaeed.github.io/issues/110)

[![RehanSaeed](https://avatars.githubusercontent.com/u/2270364?v=4)](https://github.com/RehanSaeed)

### [RehanSaeed](https://github.com/RehanSaeed)

Owner

12 May 2020

[![Igor](https://camo.githubusercontent.com/42a867d6940b0384694a2d2e01cfc0edff19e7458895665fa85d21b3787fb26b/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32393862363765363861653663313564373062386539646365663962363139653f733d393626643d6d6d26723d67)](https://camo.githubusercontent.com/42a867d6940b0384694a2d2e01cfc0edff19e7458895665fa85d21b3787fb26b/68747470733a2f2f7777772e67726176617461722e636f6d2f6176617461722f32393862363765363861653663313564373062386539646365663962363139653f733d393626643d6d6d26723d67) **[Igor](https://github.com/igorbek)** commented on **2017-01-04 01:27:59**

If you needed to use Rx's cancellation of a task, I would recommend using a proper converting by `Observable.FromAsync`:

```
public async Task WaitForFirstResultWithTimeOut()
{
    return await Observable.FromTask(ct => this.DownloadTheInternet(ct))
        .Timeout(TimeSpan.FromMilliseconds(1000))
        /*.FirstAsync()*/; // this is redundant, because IObservable is awaitable
}
```

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://rehansaeed.com/#website","@type":"WebSite","description":"Software Developer at Microsoft, YouTuber, Open Source Contributor and Blogger","inLanguage":"en-GB","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/","author":{"@id":"https://rehansaeed.com/#identity"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://rehansaeed.com/?search={search_term_string}"},"query-input":"required name=search_term_string"}],"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#webpage","@type":"WebPage","dateModified":"2017-01-02T00:00:00+00:00","datePublished":"2017-01-02T00:00:00+00:00","description":"Should you use Reactive Extensions (Rx) to do timeouts in .NET? It turns out it's better to use CancellationTokenSource in the Task Parallel Library (TPL).","name":"Reactive Extensions (Rx) - Part 8 - Timeouts","url":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/","breadcrumb":{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#breadcrumb"},"isPartOf":{"@id":"https://rehansaeed.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/"]}]},{"@id":"https://rehansaeed.com/#identity","@type":"Person","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com/about/","image":{"@id":"https://rehansaeed.com/#/schema/image/1"},"sameAs":["https://github.com/RehanSaeed","https://www.linkedin.com/in/muhammad-rehan-saeed","https://stackoverflow.com/users/1212017/muhammad-rehan-saeed","https://www.youtube.com/c/MuhammadRehanSaeed","https://www.twitch.tv/rehansaeeduk"]},{"@id":"https://rehansaeed.com/#publisher","@type":"Organization","logo":"https://rehansaeed.com/images/schema/Publisher-600x60.png","name":"Muhammad Rehan Saeed","url":"https://rehansaeed.com"},{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#article","@type":"Article","dateModified":"2017-01-02T00:00:00+00:00","datePublished":"2017-01-02T00:00:00+00:00","description":"Should you use Reactive Extensions (Rx) to do timeouts in .NET? It turns out it's better to use CancellationTokenSource in the Task Parallel Library (TPL).","headline":"Reactive Extensions (Rx) - Part 8 - Timeouts","inLanguage":"en-GB","url":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/","author":{"@id":"https://rehansaeed.com/#identity"},"image":[{"@type":"ImageObject","url":"https://rehansaeed.com/images/hero/Reactive-Extensions-1366x768.png","caption":"Reactive Extensions","width":"1366","height":"768"}],"isPartOf":{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#webpage"},"keywords":[".NET","Base Class Library","BCL","Reactive Extensions","Rx","Task Parallel Library","TPL"],"mainEntityOfPage":{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#webpage"},"publisher":{"@id":"https://rehansaeed.com/#publisher"}},{"@id":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Blog","item":"https://rehansaeed.com/","position":1},{"@type":"ListItem","name":"Reactive Extensions (Rx) - Part 8 - Timeouts","item":"https://rehansaeed.com/reactive-extensions-rx-part-8-timeouts/","position":2}]},{"@id":"https://rehansaeed.com/#/schema/image/1","@type":"ImageObject","contentUrl":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png","inLanguage":"en-GB","url":"https://rehansaeed.com/images/author/Muhammad-Rehan-Saeed/Logo-512x512.png"}]}
```

## Sitemap

See the full [sitemap](https://rehansaeed.com/sitemap.md) for all pages.
