【问题标题】:How to start a task wait for it while doing other work in the loop如何在循环中执行其他工作时启动任务等待它
【发布时间】:2019-08-12 15:10:10
【问题描述】:

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

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

// Alot of code removed for brevity sake, ignore logical errors.
string token = null;
public static async Task Send<TLog>(IEnumerable<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); 
}

【问题讨论】:

  • “但是随着 100 行的发送,我希望能够创建下一批 100 行” - 这是可能的,因为您必须等待 logBatch 列表在清除之前被处理并添加下一个日志?鉴于此,您可能需要考虑 Task.ContinueWith
  • @auburg - 一旦 API 调用“PutLogEventsAsync”,我就可以更改批处理。

标签: c# .net multithreading


【解决方案1】:

基本上你需要做的是:

  1. 创建一批日志
  2. 等待上一批当前正在处理的Put 任务(第一次通过时为空)
  3. 使用新的一批日志在后台启动一个新的Put 任务
  4. 重复

这看起来像:

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 时,您需要传入一个集合的新实例,以避免在使用该集合时对其进行修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2012-03-03
    • 1970-01-01
    • 2018-08-09
    • 2018-11-19
    • 2021-09-27
    相关资源
    最近更新 更多