如何使用任务有条件地异步运行代码

发布于 2024-12-22 14:27:54 字数 593 浏览 6 评论 0原文

我有一个负责检索资源的类,该类还缓存它们以便快速访问。 该类公开了用于检索资源的异步方法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冬天旳寂寞 2024-12-29 14:27:54

.NET 4.5 有 Task.FromResult 允许您返回 Task,但它不是在线程池线程上运行委托,而是显式设置任务的返回值。

因此,在您的代码上下文中:

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,则可以使用 TaskCompletionSource做同样的事情:

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

.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.

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

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;
海之角 2024-12-29 14:27:54

如果您有 UI 连接线程,请小心。

在 WPF 中,在 UI 线程(例如按钮单击事件处理程序)上使用 Task.Run 非常重要,以避免 UI 问题,并在后台线程上运行代码。

为什么?默认情况下,Task.Run 是 Task.Factory.StartNew 的包装器,带有 TaskScheduler.Default 参数,而不是 TaskScheduler.Current。

因此,仅仅像这样调用异步方法是不够的,因为它在 UI 线程上运行并冻结它: await SomeTaskAsync();

相反,您应该在 Task.Run 中调用它:

  • < code>Task.Run(async() =>await SomeTaskAsync());

或者在 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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文