Advertisement
Guest User

asd

a guest
Nov 24th, 2014
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1.    
  2.  
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Threading;
  6.      
  7.     namespace VPS5.LimitedConnectionsExample {
  8.         public class LimitedConnectionsExample {
  9.      
  10.             private static Semaphore pool;
  11.             private static int _padding;      
  12.      
  13.             public static void DownloadFilesAsync(IEnumerable<string> urls) {
  14.                 pool = new Semaphore(0, 10);
  15.                 foreach (var url in urls) {
  16.                     Thread t = new Thread(DownloadFile);              
  17.                     t.Start(url);
  18.                 }  
  19.                 pool.Release(10);                
  20.                
  21.             }
  22.             public static void DownloadFile(object url) {
  23.                 Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", (string)url);          
  24.                 pool.WaitOne();          
  25.                 int padding = Interlocked.Add(ref _padding, 100);
  26.                 Console.WriteLine("Thread {0} enters the semaphore.", (string)url);
  27.                 Thread.Sleep(1000 + padding);
  28.                 Console.WriteLine("Thread {0} releases the semaphore.", (string)url);
  29.                 pool.Release();
  30.             }
  31.      
  32.             public static void Main() {
  33.                 IList<String> urls = new List<String>();
  34.      
  35.                 for (int i = 1; i < 12; i++) {
  36.                     urls.Add(i.ToString());
  37.                 }
  38.                 DownloadFilesAsync(urls);
  39.             }
  40.         }
  41.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement