使用System.comvable卸载长时间的封锁呼叫以分开线程。
我想在单独的线程中执行阻塞方法。为了说明这种情况,我创建了这个示例:
int LongBlockingCall(int n)
{
Thread.Sleep(1000);
return n + 1;
}
var observable = Observable
.Range(0, 10)
.SelectMany(n =>
Observable.Defer(() => Observable.Return(LongBlockingCall(n), NewThreadScheduler.Default)));
var results = await observable.ToList();
我预计它会在约 1 秒内运行,但实际需要约 10 秒。 每次调用都应该生成一个新线程,因为我指定了 NewThreadScheduler.Default,对吗?
我做错了什么?
I want to execute a blocking method into separate threads. To illustrate the situation, I created this example:
int LongBlockingCall(int n)
{
Thread.Sleep(1000);
return n + 1;
}
var observable = Observable
.Range(0, 10)
.SelectMany(n =>
Observable.Defer(() => Observable.Return(LongBlockingCall(n), NewThreadScheduler.Default)));
var results = await observable.ToList();
I expected this to run in ~1 second, but it takes ~10 seconds instead.
A new thread should be spawned for each call, because I'm specifying NewThreadScheduler.Default
, right?
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须替换以下
线
: )“ rel =“ nofollow noreferrer”>
observable.return
只是返回一个值。它不知道该值是如何产生的。为了在特定的调度程序上调用动作,您需要observable.start
方法。You have to replace this line:
...with this:
The
Observable.Return
just returns a value. It's not aware how this value is produced. In order to invoke an action on a specific scheduler, you need theObservable.Start
method.