C# 如何在循环中执行其他工作时启动任务并等待它

C# 如何在循环中执行其他工作时启动任务并等待它,c#,.net,multithreading,C#,.net,Multithreading,我有一个API调用,每个调用接受一批100行数据,它还返回一个序列令牌,该序列令牌对于下一个调用的成功非常重要。但是,在发送100行时,我希望能够创建下一批100行,以便在上一个API调用成功后,在下一批中设置序列标记并发送它 我不知道如何实现它。我想我需要开始一项任务,然后等待它以后。下面是我的尝试,请引导我 // Alot of code removed for brevity sake, ignore logical errors. string token = null; public

我有一个API调用,每个调用接受一批100行数据,它还返回一个序列令牌,该序列令牌对于下一个调用的成功非常重要。但是,在发送100行时,我希望能够创建下一批100行,以便在上一个API调用成功后,在下一批中设置序列标记并发送它

我不知道如何实现它。我想我需要开始一项任务,然后等待它以后。下面是我的尝试,请引导我

// Alot of code removed for brevity sake, ignore logical errors.
string token = null;
public static async Task Send<TLog>(IEnummerable<TLog> logs)
{
    foreach (var log in logs)
    {

        if (logBatch.Count != 100)
            logBatch.Add(log);
        else
        {
            var response = await Put(logBatch, token); 
            token = response.NextSequenceToken; // set the sequence token for the next call
            logBatch.Clear();
            logBatch.Add(log);
        }
    }
}

public static async Task<PutLogEventsResponse> Put(List<InputLogEvent> logBatch, string token)
{
    PutLogEventsRequest req = new PutLogEventsRequest
    {
        LogEvents = logBatch,
        SequenceToken = token
    };

    return await logClient.PutLogEventsAsync(req); 
}

基本上,您需要做的是:

创建一批日志 等待前一批中当前正在处理的Put任务。第一次通过时,该任务将为空 使用新的一批日志在后台启动新的Put任务 重复 这看起来像:

Task<PutLogEventsResponse> currentPutTask = Task.FromResult<PutLogEventsResponse>(new PutLogEventsResponse { NextSequenceToken = null });
foreach (var log in logs)
{
    if (logBatch.Count != 100)
        logBatch.Add(log);
    else
    {
        token = (await currentPutTask).NextSequenceToken; // set the sequence token for the next call
        var currentBatchToProcess = new List<TLog>(logBatch);
        currentPutTask = Put(currentBatchToProcess , token);
        logBatch.Clear();
        logBatch.Add(log);
    }
}

// This line is needed so that the final batch is awaited
token = (await currentPutTask).NextSequenceToken;

请注意,当您调用Put时,您需要传入一个集合的新实例,以避免在使用集合时对其进行修改。

但是,随着100行的发送,我希望能够创建下一批100行-这是否可能,因为您必须等待处理logBatch列表,然后才能清除它并添加下一个日志?考虑到这一点,你可能需要考虑任务。ContinueWith@auburg-api调用“PutLogEventsAsync”后,我可以更改批处理。