如何使用任务有条件地异步运行代码
我有一个负责检索资源的类,该类还缓存它们以便快速访问。 该类公开了用于检索资源的异步方法:
public Task<object> GetResourceAsync(string resourceName)
{
return Task.Factory.StartNew<object>(() =>
{
// look in cache
// if not found, get from disk
// return resource
});
}
客户端代码如下所示:
myResourceProvider.GetResourceAsync("myResource")
.ContinueWith<object>(t => Console.WriteLine("Got resource " + t.Result.ToString()));
这样,始终使用后台线程。但是,如果在缓存中找到该对象,我不希望代码异步运行。 如果在缓存中找到它,我想立即返回资源,而不必使用另一个线程。
谢谢。
I have a class in charge of retrieving resources which also caches them for quick access.
The class exposes an asynchronous method for retrieving a resource:
public Task<object> GetResourceAsync(string resourceName)
{
return Task.Factory.StartNew<object>(() =>
{
// look in cache
// if not found, get from disk
// return resource
});
}
The client code then looks like this:
myResourceProvider.GetResourceAsync("myResource")
.ContinueWith<object>(t => Console.WriteLine("Got resource " + t.Result.ToString()));
This way, a background thread is always used. However, I don't want the code to run asynchronously if the object was found in the cache.
If it was found in the cache, I'd like to immediately return the resource and not to have to use another thread.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.NET 4.5 有
Task.FromResult
允许您返回Task
,但它不是在线程池线程上运行委托,而是显式设置任务的返回值。因此,在您的代码上下文中:
如果您仍在使用 .NET 4.0,则可以使用
TaskCompletionSource
做同样的事情:.NET 4.5 has
Task.FromResult
that lets you return aTask<T>
, but instead of running a delegate on a threadpool thread, it explicitly sets the task's return value.So in the context of your code:
If you're still on .NET 4.0, you can use
TaskCompletionSource<T>
to do the same thing:如果您有 UI 连接线程,请小心。
在 WPF 中,在 UI 线程(例如按钮单击事件处理程序)上使用 Task.Run 非常重要,以避免 UI 问题,并在后台线程上运行代码。
为什么?默认情况下,Task.Run 是 Task.Factory.StartNew 的包装器,带有 TaskScheduler.Default 参数,而不是 TaskScheduler.Current。
因此,仅仅像这样调用异步方法是不够的,因为它在 UI 线程上运行并冻结它:
await SomeTaskAsync();
相反,您应该在 Task.Run 中调用它:
或者在 Task.Run 中使用同步方法:
Task.Run(() =>; SomeTask());
Be careful if you have UI connected thread.
In WPF it is very important, to use the Task.Run on the UI thread (eg. a button click event handler), to avoid UI problems, and running your code on a background thread.
Why? The Task.Run by default a wrapper around the Task.Factory.StartNew with the TaskScheduler.Default parameter, instead of TaskScheduler.Current.
So not enough just to call your async method like this, because this is running on the UI thread and freezing it:
await SomeTaskAsync();
Instead of it you should call it inside a Task.Run:
Task.Run(async() => await SomeTaskAsync());
Or use your syncron method in the Task.Run:
Task.Run(() => SomeTask());