.ContinueWith()和对象状态

时间:2018-03-21 15:02:04

标签: c# lambda async-await task idisposable

我在胡扯之间更好(在美学,惯用性和表现方面):

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);
    }
}

1 个答案:

答案 0 :(得分:0)

考虑使用await而不是ContinueWith。等待的结果等于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;
    };
}