[英]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.我担心我不了解我的代码流程。
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:回答你的问题:
ssisMethod
returns before CreateAndSendReports
ssisMethod
在CreateAndSendReports
之前返回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.