围绕现有对象创建任务包装器
我有一个返回任务的方法,其中实现可能需要也可能不需要执行缓慢的操作才能检索结果。我希望能够简单地将结果值包装到一个任务中,在该值已经可用的情况下,该任务被标记为已同步完成。今天我有这样的事情:
public Task<Foo> GetFooAsync(int key) {
lock(this) {
if(_Cache.ContainsKey(key) ) {
Task<Foo> ret = new Task<Foo>(()=>_Cache[key]);
ret.RunSynchronously();
return ret;
}
else {
return Task.Factory.StartNew<Foo>(SomethingSlow());
}
}
}
是否有更简单的方法来做到这一点,当我已经知道结果时,不需要我用委托构建任务?
I have a method which returns a Task where the implementation may or may not need to perform a slow operation in order to retrieve the result. I would like to be able to simply wrap the result value into a Task which is marked as having completed synchronously in the case where the value is already available. Today I have something like this:
public Task<Foo> GetFooAsync(int key) {
lock(this) {
if(_Cache.ContainsKey(key) ) {
Task<Foo> ret = new Task<Foo>(()=>_Cache[key]);
ret.RunSynchronously();
return ret;
}
else {
return Task.Factory.StartNew<Foo>(SomethingSlow());
}
}
}
Is there is simpler way to do this that doesn't require me to construct the task with a delegate when I already know the result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 .NET 4.5 开始,您可以使用 < code>Task.FromResult() 静态方法正是用于此目的:
Beginning with .NET 4.5, you can use the
Task.FromResult<T>()
static method for exactly this purpose:您可以使用
TaskCompletionSource
:(请注意,如果
_Cache
是一个Dictionary
,您可以使用TryGetValue
使其成为单个查找。)You could use a
TaskCompletionSource<TResult>
:(Note that if
_Cache
is aDictionary<TKey, TValue>
you could useTryGetValue
to make it a single lookup.)如果您有返回结果的方法的同步版本,您可以执行以下操作
hello 方法如下所示。
If you have a synchronous version of the method that returns the result you can do the following
The hello method would look like below.