Queue of async tasks with throttling which supports muti-threading

前端 未结 5 684
傲寒
傲寒 2020-11-29 04:30

I need to implement a library to request vk.com API. The problem is that API supports only 3 requests per second. I would like to have API asynchronous.

5条回答
  •  情深已故
    2020-11-29 04:55

    You can use this as Generic

    public TaskThrottle(int maxTasksToRunInParallel)
    {
        _semaphore = new SemaphoreSlim(maxTasksToRunInParallel);
    }
    
    public void TaskThrottler(IEnumerable> tasks, int timeoutInMilliseconds, CancellationToken cancellationToken = default(CancellationToken)) where T : class
    {
        // Get Tasks as List
        var taskList = tasks as IList> ?? tasks.ToList();
        var postTasks = new List>();
    
        // When the first task completed, it will flag 
        taskList.ForEach(x =>
        {
            postTasks.Add(x.ContinueWith(y => _semaphore.Release(), cancellationToken));
        });
    
        taskList.ForEach(x =>
        {
            // Wait for open slot 
            _semaphore.Wait(timeoutInMilliseconds, cancellationToken);
            cancellationToken.ThrowIfCancellationRequested();
            x.Start();
        });
    
        Task.WaitAll(taskList.ToArray(), cancellationToken);
    }
    

提交回复
热议问题