简体   繁体   English

为什么不调用Rx.NET的Final块?

[英]Why the Rx.NET Finally block is not called?

Please, observe the following simple Rx.NET program: 请观察以下简单的Rx.NET程序:

using System;
using System.Diagnostics;
using System.Reactive.Linq;

namespace observables
{
    class Program
    {
        static void Main()
        {
            var src = Observable
                .Interval(TimeSpan.FromMilliseconds(1))
                .Take(1)
                .Do(o => Debug.WriteLine(o))
                .Finally(() => Debug.WriteLine("************ Finally"));
            src.GetAwaiter().GetResult();
        }
    }
}

It displays: 它显示:

0
************ Finally

Now, when I remove the Do block from the monad, the program does not display anything! 现在,当我从monad中删除Do块时,该程序将不显示任何内容!

Why? 为什么?

There is a race condition between the Observable thread and the Main thread. 在可观察线程和主线程之间存在竞争条件。

The function call src.GetAwaiter().GetResult(); 函数调用src.GetAwaiter().GetResult(); does not wait for the Observables Finally since it's run on different thread. 不要等待Observables Finally因为它在不同的线程上运行。

Try running it multiple times: you will see that the Debug.WriteLine succeeds occasionally, at least on my Visual Studio setup. 尝试多次运行它:至少在我的Visual Studio安装程序上,您会看到Debug.WriteLine偶尔会成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM