为什么这段代码不是异步的
据我了解 Subscribe 方法应该是异步的,而 Run 是同步的。但这段代码是以同步方式工作的。有人能修复它吗?
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("Source said there are no more messages to follow");
});
Console.WriteLine("Asynchronous");
Console.ReadKey();
}
}
}
我总是最后看到异步写入控制台。
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("Source said there are no more messages to follow");
});
Console.WriteLine("Asynchronous");
Console.ReadKey();
}
}
}
I always see Asynchronous written to console at the last.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,
Observable.Generate
使用Scheduler.CurrentThread
。但是,您可以指定不同的调度程序来获得所需的异步行为:Scheduler
类位于System.Reactive.Concurrency
命名空间中。其他可能的异步预定义调度程序是
Scheduler.TaskPool
和Scheduler.ThreadPool
。By default
Observable.Generate
usesScheduler.CurrentThread
. However, you can specify a different scheduler to get the desired asynchronous behavior:The
Scheduler
class is in theSystem.Reactive.Concurrency
namespace.Other possible asynchronous predefined schedulers are
Scheduler.TaskPool
andScheduler.ThreadPool
.