【问题标题】:How to timeout call if takes more than x milliseconds?如果需要超过 x 毫秒,如何超时调用?
【发布时间】:2020-06-05 05:59:31
【问题描述】:

我正在使用 C# 语言并正在从 cassandra 中获取数据,因此我正在使用以下代码从 Cassandra 中获取数据并且它工作正常。

我唯一的问题是我的 ProcessCassQuery 方法 - 我将 CancellationToken.None 传递给我的 requestExecuter 函数,这可能不是正确的做法。

如果查询时间超过800 milliseconds,我需要使查询超时,那么我怎样才能在此处正确使用CancellationToken 来使查询超时? Cassandra 驱动程序尚未处理CancellationToken,因此我需要通过其他方式在外部执行此操作。此代码将以非常高的吞吐量调用,因此在超时调用时需要高效..

/**
 *
 * Below method does multiple async calls on each table for their corresponding id's by limiting it down using Semaphore.
 *
 */
private async Task<List<T>> ProcessCassQueries<T>(IList<int> ids, Func<CancellationToken, int, Task<T>> mapperFunc, string msg) where T : class
{
    var tasks = ids.Select(async id => 
    {
        await semaphore.WaitAsync();
        try
        {
            return await ProcessCassQuery(ct => mapperFunc(ct, id), msg);
        }
        finally
        {
            semaphore.Release();
        }
    });

  return (await Task.WhenAll(tasks)).Where(e => e != null).ToList();
}

// this might not be good idea to do it. how can I improve below method?
private Task<T> ProcessCassQuery<T>(Func<CancellationToken, Task<T>> requestExecuter, string msg) where T : class
{
    return requestExecuter(CancellationToken.None);
}

【问题讨论】:

  • 如何添加第二个Task,它在指定的时间内除了Task.Delay 什么都不做?您必须将.WhenAll 更改为.WhenAny。然后您可以检查返回的Task 是否为超时任务并进行相应处理。
  • @imsmn 您的建议与下面安德烈的建议有什么区别?哪个更好?

标签: c# cancellationtokensource


【解决方案1】:

您可以使用以下代码:

// this might not be good idea to do it. how can I improve below method?
private async Task<T> ProcessCassQuery<T>(Func<CancellationToken, Task<T>> requestExecuter, string msg) where T : class
{
    using var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromMilliseconds(800));
    return await requestExecuter(cts.Token);
}

【讨论】:

  • 谢谢。是的,这很好用。想知道这是否是让我的通话超时的最佳方式?我只是担心,因为我的方法会以非常高的吞吐量被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
相关资源
最近更新 更多