Created
January 9, 2018 23:36
-
-
Save dezfowler/192f84096037eccba36b01568988279f to your computer and use it in GitHub Desktop.
Throttling with BlockingCollection example
This file contains 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.Collections.Concurrent; | |
using System.Linq; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace myApp | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
using (var bc = new BlockingCollection<int>(3)) | |
{ | |
// Kick off a producer task | |
Task.Factory.StartNew(() => | |
{ | |
for (int i = 0; i < 10; i++) | |
{ | |
Console.WriteLine("Trying to publish " + i); | |
bc.Add(i); | |
Console.WriteLine("Published " + i); | |
} | |
// Need to do this to keep foreach below from hanging | |
bc.CompleteAdding(); | |
}); | |
foreach (var item in bc.GetConsumingEnumerable()) | |
{ | |
Console.WriteLine("Received " + item); | |
} | |
} | |
Console.WriteLine("Done"); | |
} | |
} | |
} |
This file contains 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
Trying to publish 0 | |
Published 0 | |
Trying to publish 1 | |
Published 1 | |
Trying to publish 2 | |
Published 2 | |
Trying to publish 3 | |
Published 3 | |
Trying to publish 4 | |
Received 0 | |
Received 1 | |
Received 2 | |
Received 3 | |
Published 4 | |
Trying to publish 5 | |
Published 5 | |
Trying to publish 6 | |
Published 6 | |
Trying to publish 7 | |
Published 7 | |
Trying to publish 8 | |
Received 4 | |
Received 5 | |
Received 6 | |
Received 7 | |
Published 8 | |
Trying to publish 9 | |
Received 8 | |
Published 9 | |
Received 9 | |
Done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment