How to track if an async/awaitable task is running

后端 未结 3 1667
执笔经年
执笔经年 2020-12-17 18:14

I\'m trying to transition from the Event-based Asynchronous Pattern where I tracked running methods using unique id\'s and the asynoperationmanager.
As this has now bee

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 18:37

    SemaphoreSlim queueToAccessQueue = new SemaphoreSlim(1);
    object queueLock = new object();
    long queuedRequests = 0;
    Task _loadingTask;
    public void RetrieveItems() {
      lock (queueLock) {
          queuedRequests++;
          if (queuedRequests == 1) { // 1 is the minimum size of the queue before another instance is queued
            _loadingTask = _loadingTask?.ContinueWith(async () => {
              RunTheMethodAgain();
              await queueToAccessQueue.WaitAsync();
              queuedRequests = 0; // indicates that the queue has been cleared;
              queueToAccessQueue.Release()
            }) ?? Task.Run(async () => {
              RunTheMethodAgain();
              await queueToAccessQueue.WaitAsync();
              queuedRequests = 0; // indicates that the queue has been cleared;
              queueToAccessQueue.Release();
            });
          }
      }
    }
    public void RunTheMethodAgain() {
      ** run the method again **
    }
    

    The added bonus is that you can see how many items are sitting in the queue!

提交回复
热议问题