.ContinueWith() 和对象状态
.ContinueWith() and object state
我在犹豫哪个更好(在美学、惯用性和性能方面):
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);
}
}
考虑使用 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;
};
}
我在犹豫哪个更好(在美学、惯用性和性能方面):
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);
}
}
考虑使用 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;
};
}