How to timeout call if takes more than x milliseconds?

I am working with C# language and was working on getting data out of cassandra so I was working with below code which gets data from Cassandra and it works fine.

Only problem I have is in my ProcessCassQuery method – I am passing CancellationToken.None to my requestExecuter Function which might not be the right thing to do.

And I need to timeout the query if it takes more than 800 milliseconds so how can I use CancellationToken here properly to timeout the query? Cassandra driver doesn’t handle CancellationToken yet so I need to do this outside through some other ways. This code will be called at a very high throughput so it needs to be efficient while timing out the call.

/**
 *
 * 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);
}

Go to Source
Author: dragons