Advertisement
Guest User

Untitled

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