简体   繁体   中英

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

       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.
  2. Yes, it will wait until the ssisMethod returns before CreateAndSendReports

To achieve your goal, you can just wrap your method CreateAndSendReports to async. And create another wrapper method eg 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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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