Can a Task have multiple awaiters?

前端 未结 2 713
一整个雨季
一整个雨季 2020-12-19 02:29

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.



        
2条回答
  •  时光取名叫无心
    2020-12-19 03:06

    This code looks very "racy" if multiple threads might be involved.

    One example (I'm sure there are more). Assume that _callThisOnlyOnce is currently null:

    Thread 1                                                          Thread 2
    
    public Task CallThisOnlyOnce()
    {
      if(_callThisOnlyOnce != null && _callThisOnlyOnce.IsCompleted)
         _callThisOnlyOnce = null;
    
      if(_callThisOnlyOnce == null)
                                                                       public Task CallThisOnlyOnce()
                                                                       {
                                                                         if(_callThisOnlyOnce != null && _callThisOnlyOnce.IsCompleted)
                                                                            _callThisOnlyOnce = null;
    
                                                                         if(_callThisOnlyOnce == null)
                                                                            _callThisOnlyOnce = CallThisOnlyOnceAsync();
    
                                                                         return _callThisOnlyOnce;
                                                                       }
         _callThisOnlyOnce = CallThisOnlyOnceAsync();
    
      return _callThisOnlyOnce;
    }
    

    You now have 2 calls running simultaneously.

    As to multiple awaiters, yes you can do this. I'm sure I've seen example code from MS somewhere showing an optimization where e.g. the result of Task.FromResult(0) is stored away in a static member and returned any time the function wants to return zero.

    I have, however, been unsuccessful in locating this code sample.

提交回复
热议问题