[英]TaskCompletionSource for Task
如何为Task
而不是Task<TResult>
创建TaskCompletionSource
?
There is no non-generic version. 没有非通用版本。 However,
Task<T>
derives from Task
, so you can just use TaskCompletionSource<bool>
and return the task. 但是,
Task<T>
派生自Task
,因此您可以只使用TaskCompletionSource<bool>
并返回任务。
Task SomeMethodAsync()
{
var tcs = new TaskCompletionSource<bool>();
// Implement method as needed
return tcs.Task; // Return the Task<bool> as a Task
}
Note that I'm using bool
just because it's a small value type, and the result will get "thrown away". 请注意,我使用
bool
只是因为它是一个小值类型,结果将被“扔掉”。 Another option here is to make your own custom type and return that, ie: 这里的另一个选择是创建您自己的自定义类型并返回它,即:
private struct EmptyType {}
Task SomeMethodAsync()
{
var tcs = new TaskCompletionSource<EmptyType>();
// Implement method as needed
// Use tcs.SetResult(default(EmptyType)) or similar
return tcs.Task; // Return the Task<bool> as a Task
}
The main advantage here is the type is the smallest possible (least waste), and a type that doesn't suggest there is a "value" contained within the result (if the consumer does use reflection, etc). 这里的主要优点是类型尽可能小(浪费最少),并且类型不建议结果中包含“值”(如果消费者确实使用了反射等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.