5

I am playing with Rx in .Net3.5SP1 and trying the 101 Rx Samples. I am trying the first sample (Start - Run Code Asynchronously) but it doesn't seem to actually run asynchronously. For example,

        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]");

Outputs

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

Is there an explanation for this? Am I doing something wrong? Is this expected behaviour?

UPDATE

I would have thought it would have said

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

But the main thread is blocked while the supposedly Asynch call happens.

4

3 回答 3

1

这在我看来是合理的。

如果你Thread.Sleep在“Created”和“Starting”之间进行调用,我想你会看到“Calculating”行出现,表明它在主线程运行时正在工作。这就是异步的方式。

如果您担心是因为First()返回值本身,而不是给出一种您可以稍后查阅的“未来”值,那是另一回事 - 我有两篇博文供您阅读:第 1 部分第 2 部分。我你想要这个Prune方法,但我不完全确定。

于 2010-02-19T19:57:31.280 回答
1

该行// subscribe and wait for completion of background operation表示它等待后台操作完成。因此,您不会期望该行 ( Console.WriteLine("[Started]");) 之后的代码在操作完成之前运行,对吗?

于 2010-02-19T20:12:45.340 回答
1

首先是阻塞......订阅是你想要的:

        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();
    }
于 2010-03-01T17:04:29.917 回答