Queuing asynchronous task in C#

前端 未结 4 1041
慢半拍i
慢半拍i 2021-01-28 14:46

I have few methods that report some data to Data base. We want to invoke all calls to Data service asynchronously. These calls to data service are all over and so we want to mak

4条回答
  •  -上瘾入骨i
    2021-01-28 15:07

    One option is to queue operations that will create tasks instead of queuing already running tasks as the code in the question does.

    PseudoCode without locking:

     Queue> tasksQueue = new Queue>();
    
     async Task RunAllTasks()
     {
          while (tasksQueue.Count > 0)
          { 
               var taskCreator = tasksQueue.Dequeu(); // get creator 
               var task = taskCreator(); // staring one task at a time here
               await task; // wait till task completes
          }
      }
    
      // note that declaring createSaveModuleTask does not  
      // start SaveModule task - it will only happen after this func is invoked
      // inside RunAllTasks
      Func createSaveModuleTask = () => SaveModule(setting);
    
      tasksQueue.Add(createSaveModuleTask);
      tasksQueue.Add(() => SaveModule(GetAdvancedData(setting)));
      // no DB operations started at this point
    
      // this will start tasks from the queue one by one.
      await RunAllTasks();
    

    Using ConcurrentQueue would be likely be right thing in actual code. You also would need to know total number of expected operations to stop when all are started and awaited one after another.

提交回复
热议问题