小编Dan*_*ber的帖子

配置TaskCompletionSource的任务的延续行为

请考虑以下代码:

public Task SomeAsyncMethod()
{
    var tcs = new TaskCompletionSource();
    ... do something, NOT setting the TaskCompletionSource...

    return tcs.Task
}

public void Callsite1()
{
    await SomeAsyncMethod();
    Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}

public void Callsite2()
{
    SomeAsyncMethod().ContinueWith((task) =>
    {
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
    });
}
Run Code Online (Sandbox Code Playgroud)

在某个时间点,在SomeAsyncMethod中创建的TaskCompletionSource是在ThreadPool线程上设置的:

Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
tcs.SetResult();
Run Code Online (Sandbox Code Playgroud)

当等待来自TaskCompletionSource的Task(如在Callsite1中)时,继续在调用SetResult的Thread上同步执行.调用ContinueWith时(如在Callsite2中),继续在另一个线程上异步执行.

调用configure await是没有用的,如

public void Callsite1()
{
    await SomeAsyncMethod().ConfigureAwait(true or false);
}
Run Code Online (Sandbox Code Playgroud)

这甚至不是这个问题的重点.作为SomeAsyncMethod的实现者,我不想通过调用SetResult来调用一些可能未知的代码.我希望延迟始终是异步安排的.而且我不能依赖调用者来正确配置await(如果这甚至可以工作).

如何配置TaskCompletionSource,使其任务在等待时不会同步执行其继续?

.net c# clr task-parallel-library async-await

4
推荐指数
1
解决办法
1864
查看次数

标签 统计

.net ×1

async-await ×1

c# ×1

clr ×1

task-parallel-library ×1