简体   繁体   English

线程循环的异步基础

[英]Async fundamentals for threading a loop

I am hoping this is a pretty simple example of code that I am trying to understand.我希望这是我试图理解的一个非常简单的代码示例。

I would like to keep starting the process over while waiting for a long running process to complete.我想在等待长时间运行的过程完成时继续重新启动该过程。 The goal is to run all batches at the same time.目标是同时运行所有批次。 For example:例如:

while(moreToProcess())
{
   var batch = CreateBatch();
   await ssisMethod(batch); //takes 30 seconds and would like to start next batch
   CreateAndSendReports(batch); //Must wait for ssisMethod to complete
}

I am concerned I don't understand the flow of my code.我担心我不了解我的代码流程。

  1. Will it kick off another batch while waiting?它会在等待时启动另一批吗?
  2. Will it wait to complete before creating reports?在创建报告之前会等待完成吗?

as requested:按照要求:

The important part i think:我认为的重要部分:

      public static async Task ssisMehtod(varBatch)
      {                      
            using (OleDbConnection conn = new OleDbConnection(cstr))
            {
                using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    cmd.Parameters.Add("@p1", OleDbType.Integer).Value = batchID;
                    cmd.Parameters.Add("@p2", OleDbType.VarWChar, 9).Value = DUNS;
                    conn.Open();
                    await cmd.ExecuteNonQueryAsync();
                }
            }
       }

You can save all tasks and run them together after the WhenAll code continues您可以保存所有任务并在 WhenAll 代码继续后一起运行它们

       var tasks = new List<Task>();

        while (condition is true)
        {
            tasks.Add(Task.Run(async () =>
            {
                var batch = CreateBatch();
                await ssisMethod(batch); 
                CreateAndSendReports(batch); 
            }));
        }

        Task.WhenAll(tasks);

To answer you question:回答你的问题:

  1. No, It will not kick off another batch while waiting.不,它不会在等待时启动另一批。 What it does is just free up the main thread, so your main thread/UI thread won't hang there.它所做的只是释放主线程,因此您的主线程/ UI 线程不会挂在那里。
  2. Yes, it will wait until the ssisMethod returns before CreateAndSendReports是的,它会等到ssisMethodCreateAndSendReports之前返回

To achieve your goal, you can just wrap your method CreateAndSendReports to async.为了实现您的目标,您可以将您的方法CreateAndSendReports包装为异步。 And create another wrapper method eg ProcessBatch .并创建另一个包装方法,例如ProcessBatch

public static async Task ProcessBatch(Batch batch)
{
  await ssisMethod(batch).ConfigureAwait(false);
  await CreateAndSendReports(batch).ConfigureAwait(false);
}

while(moreToProcess())
{
   var batch = CreateBatch();
   ProcessBatch(batch).ConfigureAwait(false); //Program will not wait here, it will proceed to create another batch.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM