gpt4 book ai didi

asynchronous - 任务.继续困惑

转载 作者:行者123 更新时间:2023-12-04 18:46:20 29 4
gpt4 key购买 nike

使用 ASP.NET 4.5,我正在尝试使用新的 async/await 玩具。我有一个 IDataReader 实现类,它包装了一个特定于供应商的阅读器(如 SqlDatareader)。我有一个简单的 ExecuteSql() 方法,它像这样同步运行:

public IDataReader ReaderForSql(string sql)
{
var cmd = NewCommand(sql, CommandType.Text);
return DBReader.ReaderFactory(cmd.ExecuteReader());
}

我想要的是这个的异步版本。这是我的第一次尝试:
public Task<IDataReader> ReaderForSqlAsync(string sql, CancellationToken ct)
{
var cmd = NewCommand(sql, CommandType.Text);
return cmd.ExecuteReaderAsync(ct)
.ContinueWith(t => DBReader.ReaderFactory(t.Result));
}

我使用它:
using (var r = await connection.ReaderForSqlAsync("SELECT ...", cancellationToken))
{
...
}

到目前为止,这在我有限的测试中非常有效。但是看了几遍这个Cloud9视频后: http://channel9.msdn.com/Events/aspConf/aspConf/Async-in-ASP-NET我对他们给出的警告感到担忧:
  • 继续消耗额外的线程池资源 - Readerfactory 很轻!
  • Task.Result 阻塞

  • 并且由于我将 ContinuationToken 传递给 ExecuteReaderAsync() 似乎取消只是 ExecuteReaderAsync() 可能失败的另一个原因(毕竟它是 SQL!)

    当我尝试 ContinueWith 时,任务的状态是什么? t.Result 会阻塞吗?扔?做错事?

    最佳答案

    ContinueWith默认情况下将使用当前的任务调度程序(线程池线程),但您可以通过传递 TaskContinuationOptions.ExecuteSynchronously 来更改它。和明确的 TaskScheduler .

    也就是说,我会把它作为第一次尝试:

    public async Task<IDataReader> ReaderForSqlAsync(string sql, CancellationToken ct)
    {
    var cmd = NewCommand(sql, CommandType.Text);
    var readerResult = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
    return DBReader.ReaderFactory(readerResult);
    }
    asyncawait处理所有 ContinueWith以一致的方式为您提供美味佳肴和边缘条件。可能会将此代码复杂化以使其更快 如果 性能测试表明这是一个严重的问题。

    关于asynchronous - 任务.继续困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651383/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com