Thursday, September 5, 2013

C#: SEMAPHORE - Run a number of threads at a time

 Here we have 10 scripts and we want to run 3 scripts only at at time.

public partial class Semaphore
{
 static SemaphoreSlim _sem = new SemaphoreSlim(3);
 string scriptMonitoring = string.Empty;

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
    for (int i = 1; i <= 10; i++)
    {
     new Thread(Enter).Start(i);
    }
 }

 void Enter(object id)
 {
  scriptMonitoring += String.Format("\nScript {0} wants to crawl.", id);
  _sem.Wait();
  scriptMonitoring += String.Format("\nScript {0} is now crawling.", id);
  Thread.Sleep(1000 * (int) id);
  scriptMonitoring += String.Format("\nScript {0} has stopped crawling.", id);
  _sem.Release();
 }
}

-----
Script 1 wants to crawl.
Script 1 is now crawling.
Script 2 wants to crawl.
Script 2 is now crawling.
Script 3 wants to crawl.
Script 3 is now crawling.
Script 4 wants to crawl.
Script 5 wants to crawl.
Script 6 wants to crawl.
Script 7 wants to crawl.
Script 9 wants to crawl.
Script 8 wants to crawl.
Script 10 wants to crawl.
Script 1 has stopped crawling.
Script 4 is now crawling.
Script 2 has stopped crawling.
Script 5 is now crawling.
Script 3 has stopped crawling.
Script 6 is now crawling.
Script 4 has stopped crawling.
Script 7 is now crawling.
Script 5 has stopped crawling.
Script 9 is now crawling.
Script 6 has stopped crawling.
Script 8 is now crawling.
Script 7 has stopped crawling.
Script 10 is now crawling.
Script 8 has stopped crawling.
Script 10 has stopped crawling.
Script 9 has stopped crawling.

No comments:

Post a Comment