一个任务可以有多个等待者吗? [英] Can a Task have multiple awaiters?

查看:34
本文介绍了一个任务可以有多个等待者吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Windows 8 项目提供异步服务,并且该服务有一些异步调用,一次只能调用一次.

I am toying around with an async service for a Windows 8 project and there are some async calls of this service, which should only be called once at a time.

 public async Task CallThisOnlyOnce()
 {
      PropagateSomeEvents();

      await SomeOtherMethod();

      PropagateDifferentEvents();
 }

由于不能在 lock 语句中封装异步调用,我想到了使用 AsyncLock 模式,但比我想的还不如尝试这样的方法:

Since you cannot encapsulate an async call in a lock statement, i thought of using the AsyncLock pattern, but than i thought i might as well try something like this:

 private Task _callThisOnlyOnce;
 public Task CallThisOnlyOnce()
 {
      if(_callThisOnlyOnce != null && _callThisOnlyOnce.IsCompleted)
         _callThisOnlyOnce = null;

      if(_callThisOnlyOnce == null)
         _callThisOnlyOnce = CallThisOnlyOnceAsync();

      return _callThisOnlyOnce;
 }

 private async Task CallThisOnlyOnceAsync()
 {
      PropagateSomeEvents();

      await SomeOtherMethod();

      PropagateDifferentEvents();
 }

因此,您最终只会同时执行一次 CallThisOnlyOnceAsync 调用,并且多个等待者挂在同一个任务上.

Therefore you would end up with the call CallThisOnlyOnceAsync only executed once simultanously, and multiple awaiters hooked on the same Task.

这是一种有效"的方法还是这种方法有一些缺点?

Is this a "valid" way of doing this or are there some drawbacks to this approach?

推荐答案

一个任务可以有多个等待者.但是,正如 Damien 指出的那样,您提出的代码存在严重的竞争条件.

A task can have multiple awaiters. However, as Damien pointed out, there's serious race conditions with your proposed code.

如果您希望每次调用您的方法时都执行代码(但不是同时),请使用 AsyncLock.如果您希望代码只执行一次,请使用 AsyncLazy.

If you want the code executed each time your method is called (but not simultaneously), then use AsyncLock. If you want the code executed only once, then use AsyncLazy.

您提议的解决方案尝试组合多个调用,如果代码尚未运行,则再次执行该代码.这更棘手,解决方案在很大程度上取决于您需要的确切语义.这是一种选择:

Your proposed solution attempts to combine multiple calls, executing the code again if it is not already running. This is more tricky, and the solution heavily depends on the exact semantics you need. Here's one option:

private AsyncLock mutex = new AsyncLock();
private Task executing;

public async Task CallThisOnlyOnceAsync()
{
  Task action = null;
  using (await mutex.LockAsync())
  {
    if (executing == null)
      executing = DoCallThisOnlyOnceAsync();
    action = executing;
  }

  await action;
}

private async Task DoCallThisOnlyOnceAsync()
{
  PropagateSomeEvents();

  await SomeOtherMethod();

  PropagateDifferentEvents();

  using (await mutex.LockAsync())
  {
    executing = null;
  }
}

也可以使用 Interlocked 来做到这一点,但代码变得难看.

It's also possible to do this with Interlocked, but that code gets ugly.

附言我的 AsyncEx 库.

P.S. I have AsyncLock, AsyncLazy, and other async-ready primitives in my AsyncEx library.

这篇关于一个任务可以有多个等待者吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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