【问题标题】:.ContinueWith() and object state [duplicate].ContinueWith() 和对象状态
【发布时间】:2018-03-21 15:02:03
【问题描述】:

我在哪个更好(在美学、惯用语和性能方面)之间犹豫不决:

public async Task<string> DecryptAsync(string encrypted)
{
    SymmetricAlgorithm aes = this.GetAes();

    return await this.DecryptAsync(aes, encrypted).ContinueWith(
        (decryptTask, objectState) =>
        {
            (objectState as IDisposable)?.Dispose();
            return decryptTask.Result;
        },
        aes);
}

public async Task<string> DecryptAsync(string encrypted)
{
    SymmetricAlgorithm aes = this.GetAes();

    return await this.DecryptAsync(aes, encrypted).ContinueWith(decryptTask =>
    {
        aes.Dispose();
        return decryptTask.Result;
    });
}

主要区别在于第二个捕获 lambda 中的 aes 变量,而第一个将其作为参数传递,然后将其转换为适当的类型。

第三个考虑因素,灵感来自 OxaldServy

public async Task<string> DecryptAsync(string encrypted)
{
    using (SymmetricAlgorithm aes = this.GetAes())
    {
        return await this.DecryptAsync(aes, encrypted);
    }
}

【问题讨论】:

  • 我一直认为,如果可以避免强制转换,那就避免它。
  • 我想知道“using(SymmetricAlgorithm aes = this.GetAes())”是否是一个更好的工作解决方案,因为“using”语句已经与 IEnumerable/yield 模式一起正常工作。
  • 如果您实际上并未使用await,为什么还要用async-await 标记问​​题?更重要的是,你为什么不使用await
  • @Oxald yours 是一个很好的问题——我之所以选择这个设计是因为HttpClientHttpResponseMessage 如果HttpResponseMessage 被包裹在using 中,Content.ReadAsStreamAsync 将无效它会在从蒸汽中读取之前Dispose(),使其无效。 ContinueWith() 模式成为解决方案的一部分。
  • @Servy 抱歉,由于 ReSharper 提示,我在该级别省略了它。暂时把它们放回去。

标签: c# lambda async-await task idisposable


【解决方案1】:

考虑使用 await 而不是 ContinueWith。 await 的结果等于 Task.Result。可以使用 using 语句来处理 aes:

public async Task<string> DecryptAsync(string encrypted)
{
    using (SymmetricAlgorithm aes = this.GetAes())
    {
        string decryptedText = await this.DecryptAsync(aes, encrypted);
        return decryptedText;
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多