如果超过 x 毫秒,如何超时调用?
How to timeout call if takes more than x milliseconds?
我正在使用 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);
}
您可以使用以下代码:
// 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);
}
我正在使用 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);
}
您可以使用以下代码:
// 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);
}