ToTask使OnCompleted在不同的线程上执行

时间:2015-08-04 11:34:05

标签: task-parallel-library system.reactive

代码:

[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design", "System.Drawing.Design.UITypeEditor, System.Drawing")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<string> TestList { get; set; }

public ListTest()
{
    TestList = new List<string>();
}

输出:

var sc = new TestScheduler();

Observable.Timer(TimeSpan.FromSeconds(5), sc)
          .ToTask()
          .ToObservable()
          .Do(_ => Console.WriteLine("on next: " + Thread.CurrentThread.ManagedThreadId), 
             () => Console.WriteLine("on complete: " + Thread.CurrentThread.ManagedThreadId))
          .Subscribe();

Console.WriteLine("call: " + Thread.CurrentThread.ManagedThreadId);
sc.AdvanceBy(TimeSpan.FromSeconds(5).Ticks);

如果同时删除ToTask和ToObservable,则所有内容都将在同一个线程上执行。在我看来,TPL以某种方式调度OnCompleted到任务池,但我在源代码中找不到它。

有人能帮我理解这里发生了什么吗?

DotNetFiddle链接:https://dotnetfiddle.net/epqTAG

1 个答案:

答案 0 :(得分:3)

Task.ToObservable()使用Task.ContinueWith()添加Task continuation以在任务完成时触发observable。默认情况下,Task.ContinueWith()会在任务池上安排继续。

Rx.Net最近添加了ToObservable的重载,接受IScheduler

有关详细信息,请参阅Rx.Net github issue