Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading;
- namespace VPS5.LimitedConnectionsExample {
- public class LimitedConnectionsExample {
- private static Semaphore pool;
- private static int _padding;
- public static void DownloadFilesAsync(IEnumerable<string> urls) {
- pool = new Semaphore(0, 10);
- foreach (var url in urls) {
- Thread t = new Thread(DownloadFile);
- t.Start(url);
- }
- pool.Release(10);
- }
- public static void DownloadFile(object url) {
- Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", (string)url);
- pool.WaitOne();
- int padding = Interlocked.Add(ref _padding, 100);
- Console.WriteLine("Thread {0} enters the semaphore.", (string)url);
- Thread.Sleep(1000 + padding);
- Console.WriteLine("Thread {0} releases the semaphore.", (string)url);
- pool.Release();
- }
- public static void Main() {
- IList<String> urls = new List<String>();
- for (int i = 1; i < 12; i++) {
- urls.Add(i.ToString());
- }
- DownloadFilesAsync(urls);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement