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.
.NET 4.5 has
Task.FromResultthat 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: