我正在.net3.5sp1中与RX一起玩,并尝试 101个RX样品. 。我正在尝试第一个示例(启动 - 不同步运行代码),但它似乎并没有实际运行。例如,

        Console.WriteLine("[Creating]");
        var o = Observable.Start(() => 
        {
            Console.WriteLine("Calculating..."); 
            Thread.Sleep(3000); 
            Console.WriteLine("Done."); 
        });
        Console.WriteLine("[Created]");
        Console.WriteLine("[Starting]");
        o.First();   // subscribe and wait for completion of background operation
        Console.WriteLine("[Started]");

输出

[Creating]
[Created]
[Starting]
Calculating...
    <...3 Second Wait...>
Done.
[Started]

有解释吗?难道我做错了什么?这是预期的行为吗?

更新

我会以为会说的

[Creating] 
[Created] 
[Starting] 
Calculating... 
[Started] 
    <...3 Second Wait...> 
Done. 

但是,当据说异步调用发生时,主线程被阻止。

有帮助吗?

解决方案

这对我来说似乎很合理。

如果你把 Thread.Sleep 在“创建”和“启动”之间调用,我认为您会看到“计算”行出现,表明它在主线程运行时正在执行工作。那就是它的异步。

如果您担心的话,因为 First() 返回价值本身,而不是给您以后可以咨询的“未来”价值,这是另一回事 - 我有两个博客文章供您阅读: 第1部分; 第2部分. 。我 思考 你想要 Prune 方法,但我不确定。

其他提示

线 // subscribe and wait for completion of background operation 说它等待背景操作完成。因此,您不会期望遵循该行的代码(Console.WriteLine("[Started]");)运行直到操作完成,对吗?

首先是阻止...订阅是您想要的:

        public static void Main(string[] args) {

        Console.WriteLine("[Creating]");
        var o = Observable.Start(() =>
        {
            Console.WriteLine("Calculating...");
            Thread.Sleep(3000);

        });
        Console.WriteLine("[Created]");
        Console.WriteLine("[Starting]");

        o.Subscribe(_ => Console.WriteLine("Done."));   // subscribe and wait for completion of background operation 

        Console.WriteLine("[Started]");

        Console.ReadKey();
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top