如何解决为什么延续异步执行?
下面的代码示例
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 举报,一经查实,本站将立刻删除。