为什么延续异步执行?

问题描述

下面的代码示例

public static void test()
{
    taskcompletionsource<bool> inner = new taskcompletionsource<bool>();
    taskcompletionsource<bool> outer = new taskcompletionsource<bool>();
    TaskScheduler ctScheduler = new CurrentThreadTaskScheduler();

    outer.Task.ContinueWith(
        completedTask =>
        {
            Console.WriteLine("Continuation of the outer in the thread #{0}",Thread.CurrentThread.ManagedThreadId);
            inner.SetResult(true);
        },CancellationToken.None,TaskContinuationoptions.None,TaskScheduler.Default);

    Task t = Task.Run(
        async () =>
        {
            await inner.Task;
            Console.WriteLine("Awaiter continuation in the thread #{0}",Thread.CurrentThread.ManagedThreadId);
        });

    Thread.Sleep(1000);
    Console.WriteLine("Setting the outer to completed in the thread #{0}",Thread.CurrentThread.ManagedThreadId);
    outer.SetResult(true);
}

产生以下输出

在线程#1中设置outer为完成
线程中外部的延续#4
线程 #4 中的等待程序延续

正如预期的那样,await inner.Task之后的continuation在完成任务的线程上同步执行,即线程#4。
当我尝试在同一个当前线程上同步运行所有延续时

outer.Task.ContinueWith(
completedTask =>
{
    Console.WriteLine("Continuation of the outer in the thread #{0}",Thread.CurrentThread.ManagedThreadId);
    inner.SetResult(true);
},ctScheduler);

使用一个简单的自定义任务调度器,实现如下

public sealed class CurrentThreadTaskScheduler : TaskScheduler
{
    protected override IEnumerable<Task> GetScheduledTasks()
    {
        return Enumerable.Empty<Task>();
    }

    protected override void QueueTask(Task task)
    {
        this.TryExecuteTask(task);
    }

    protected override bool TryExecuteTaskInline(Task task,bool taskwasprevIoUslyQueued)
    {
        return this.TryExecuteTask(task);
    }
}

'awaiter' 延续异步运行,如下面的输出所示

在线程#1中设置outer为完成
线程中外部的延续#1
线程 #4 中的等待程序延续

为什么有问题的延续是异步运行的,我应该如何实现调度程序来保证预期的行为?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)