Created
May 5, 2014 14:37
-
-
Save Spaider/8898b42ada76c5b9c3e3 to your computer and use it in GitHub Desktop.
Task throttling using TAP and .NET v4.5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace ProducerConsumerTest | |
{ | |
class Program | |
{ | |
private const int MAX_CONCURRENCY_LEVEL = 5; | |
private const int NUM_PAGES = 20; | |
private static List<Task<int>> _taskList; | |
static void Main(string[] args) | |
{ | |
var task = MainInternal(); | |
task.Wait(); | |
Console.WriteLine("All tasks completed"); | |
Console.ReadKey(); | |
} | |
private static async Task MainInternal() | |
{ | |
_taskList = new List<Task<int>>(); | |
var p = 1; | |
while (p <= NUM_PAGES && p < MAX_CONCURRENCY_LEVEL) | |
{ | |
_taskList.Add(SampleTaskAsync(p)); | |
p++; | |
} | |
while (_taskList.Count > 0) | |
{ | |
var finishedTask = await Task.WhenAny(_taskList); | |
_taskList.Remove(finishedTask); | |
if (p > NUM_PAGES) | |
{ | |
continue; | |
} | |
_taskList.Add(SampleTaskAsync(p)); | |
p++; | |
} | |
} | |
private static async Task<int> SampleTaskAsync(int pageNo) | |
{ | |
var rnd = new Random((int)DateTime.Now.Ticks); | |
var delay = rnd.Next(2000) + 500; | |
Console.WriteLine("Sending page {0}, delay is {1} ms", pageNo, delay); | |
await Task.Delay(delay); | |
return pageNo; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment