Rx在C#里执行顺序不一致的问题

这段代码五秒输出一个数字,执行顺序看起来和foreach差不多

var _delayObservable = Observable.Create<int>((observer) =>
{
    Observable.Range(1, 5).Select(i =>
    {
        Thread.Sleep(TimeSpan.FromSeconds(0.5));
        return i;
    }).Subscribe(observer);
    Console.WriteLine("End");
    return () => { };
});
_delayObservable.Subscribe(
    Console.WriteLine,
    () => Console.WriteLine("Completed"));

输出

End
1
2
3
4
5
Completed

然后这段代码我把Sleep放到了一个新的Thread里……结果执行顺序就不一样了orz……这是什么原因呢?

var _delayObservable = Observable.Create<int>((observer) =>
{
    Thread thread = new Thread(() =>
    {
        Observable.Range(1, 5).Select(i =>
        {
            Thread.Sleep(TimeSpan.FromSeconds(0.5));
            return i;
        }).Subscribe(observer);
        Console.WriteLine("End");
    });
    thread.Start();
    return () => { };
});
_delayObservable.Subscribe(
    Console.WriteLine,
    () => Console.WriteLine("Completed"));

输出

1
2
3
4
5
Completed
End
查看回复