开发者

Why isn't this code behaving asynchronous

开发者 https://www.devze.com 2023-04-03 06:51 出处:网络
As I understand Subscribe method should be asynchronous whereas Run is synchronous. But this piece of code is working in synchronous manner. Can anybody fix it?

As I understand Subscribe method should be asynchronous whereas Run is synchronous. But this piece of code is working in synchronous manner. Can anybody fix it?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive.Linq;

namespace RxExtensionsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IObservable<int> source = Observable.Generate<int, int>(0, i => i < 10000, i => i + 1, i => i * i);

            IDisposable subscription = source.Subscribe(x => { Console.WriteLine("Received {0} from source", x); }, ex =>
            {
                Console.WriteLine("Error occured");

            }, () =>
            {
                Console.WriteLine开发者_JAVA百科("Source said there are no more messages to follow");
            });

            Console.WriteLine("Asynchronous");

            Console.ReadKey();
        }
    }
}

I always see Asynchronous written to console at the last.


By default Observable.Generate uses Scheduler.CurrentThread. However, you can specify a different scheduler to get the desired asynchronous behavior:

IObservable<int> source = Observable.Generate<int, int>(
  0,
  i => i < 10000,
  i => i + 1,
  i => i * i,
  Scheduler.NewThread
);

The Scheduler class is in the System.Reactive.Concurrency namespace.

Other possible asynchronous predefined schedulers are Scheduler.TaskPool and Scheduler.ThreadPool.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号