【发布时间】: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 变量,而第一个将其作为参数传递,然后将其转换为适当的类型。
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 是一个很好的问题——我之所以选择这个设计是因为
HttpClient的HttpResponseMessage如果HttpResponseMessage被包裹在using中,Content.ReadAsStreamAsync将无效它会在从蒸汽中读取之前Dispose(),使其无效。ContinueWith()模式成为解决方案的一部分。 -
@Servy 抱歉,由于 ReSharper 提示,我在该级别省略了它。暂时把它们放回去。
标签: c# lambda async-await task idisposable