为什么这段代码不是异步的

发布于 2024-12-03 19:45:32 字数 904 浏览 0 评论 0原文

据我了解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╭ゆ眷念 2024-12-10 19:45:32

默认情况下,Observable.Generate 使用Scheduler.CurrentThread。但是,您可以指定不同的调度程序来获得所需的异步行为:

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

Scheduler 类位于 System.Reactive.Concurrency 命名空间中。

其他可能的异步预定义调度程序是 Scheduler.TaskPoolScheduler.ThreadPool

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文