我最近接触了C#语言并致力于从cassandra中获取数据。下面的代码可以从Cassandra中获取数据并且它能正常工作。
我唯一遇到的问题是在ProcessCassQuery
方法中,我将CancellationToken.None
传递给了我的requestExecuter
函数,这可能不是正确的做法。应该如何处理这种情况,并采取什么措施来正确处理它?
/**
*
* 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
{
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);
}
CancellationTokenSource
,然后传递一个对你的Func<T>
的引用 -- 你需要检查是否调用了Cancel()
方法。我将写一个快速示例。 - Glenn Ferrie