如何使用任务有条件地运行code asynchonously [英] How to conditionally run a code asynchonously using tasks

查看:98
本文介绍了如何使用任务有条件地运行code asynchonously的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类负责获取资源,这也对其进行缓存以便快速访问的。 该类公开了一个异步方法检索资源:

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
    });
}

客户端code,那么看起来是这样的:

The client code then looks like this:

myResourceProvider.GetResourceAsync("myResource")
    .ContinueWith<object>(t => Console.WriteLine("Got resource " + t.Result.ToString()));

这样,一个后台线程始终使用。不过,我不希望code异步运行,如果该对象是在缓存中找到。 如果它被发现在缓存中,我想立即返回的资源,而不是必须使用另一个线程。

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.

感谢。

推荐答案

.NET 4.5有<一个href="http://msdn.microsoft.com/en-us/library/hh194922%28v=vs.110%29.aspx"><$c$c>Task.FromResult让您返回任务&LT; T&GT;的,而是在一个线程池线程运行的一个代表,它明确规定了任务的返回值

.NET 4.5 has Task.FromResult that lets you return a Task<T>, but instead of running a delegate on a threadpool thread, it explicitly sets the task's return value.

所以在你的code的范围内:

So in the context of your code:

public Task<object> AsyncGetResource(string resourceName)
{
    object valueFromCache;
    if (_myCache.TryGetValue(resourceName, out valueFromCache)) {
        return Task.FromResult(valueFromCache);
    }
    return Task.Factory.StartNew<object>(() =>
    {
        // get from disk
        // add to cache
        // return resource
    });
}

如果你仍然在.NET 4.0中,你可以使用<一个href="http://msdn.microsoft.com/en-us/library/dd449174.aspx"><$c$c>TaskCompletionSource<T>做同样的事情:

If you're still on .NET 4.0, you can use TaskCompletionSource<T> to do the same thing:

var tcs = new TaskCompletionSource<object>();
tcs.SetResult(...item from cache...);
return tcs.Task;

这篇关于如何使用任务有条件地运行code asynchonously的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆