FromAsync with CancellationToken


  • I observe a strange behavior of the Observable.FromAsync factory method with CancellationToken. Consider this short program:

    void Test()
        Console.WriteLine("-- Task call");
        using (var cts = new CancellationTokenSource())
            var t = ComputeNumber(cts.Token);
            Console.WriteLine("Task result: {0}", t.Result);
        Console.WriteLine("-- Observable call");
        IObservable<int> s = Observable.FromAsync<int>(ComputeNumber);
        Console.WriteLine("Observable result: {0}", s.Wait());
    async Task<int> ComputeNumber(CancellationToken ct)
        ct.Register(() => { Console.WriteLine("Register callback called"); });
        await Task.Delay(1000, ct);
        return 1;

    The program invokes the asynchronous ComputeNumber method twice. First by Task methods directly, second using FromAsync Rx method. In the first execution with Task, the CancellationToken registered callback is not called. But in the second execution with Rx it is, which makes no sense to me. The computation is not canceled, so why is that? Is it meant as some kind of cleaning up?

    Is this inconsistency intentional? Or am I missing something?

    Friday, January 24, 2014 9:11 AM