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.

Tuesday, September 3, 2013

Thread Locking

When sharing data between threads using static fields, chances are that the unique fields will be accessed/evaluated twice. Using an exclusive lock fixes this.

    class Program
    {
        static bool done;
        static readonly object locker = new object();

        static void Main(string[] args)
        {
            new Thread(Go).Start();
            Go();
        }

        static void Go()
        {
            lock (locker)
            {
                if (!done)
                {
                    Console.WriteLine("Completed."); //this must be accessed once
                    done = true;
                }
            }
            Console.ReadKey();
        }
    }

Simple SQL

public static DataTable GetAddressFromDB()
{
    string MyConString = "server=192.168.2.213;database=hotel;Username=root;Password=crawl;";
    MySqlConnection conn = new MySqlConnection(MyConString);

    MySqlCommand command = conn.CreateCommand();

    string dbQuery = String.Format(@"SELECT
                    suburb_city_id as SuburbCityId,
                    LOWER(TRIM(suburb_city_name)) as SuburbCityName,
                    LOWER(TRIM(main_country_state.state_name)) as StateName,
                    LOWER(TRIM(main_country.country_name)) as CountryName
                    FROM main_suburb_city
                    LEFT JOIN main_country_state
                      ON main_country_state.state_id = main_suburb_city.state_id
                    LEFT JOIN main_country
                      ON main_country.country_id = main_suburb_city.country_id
                    ORDER BY main_suburb_city.suburb_city_name;");

    MySqlCommand cmd = new MySqlCommand(dbQuery, conn);

    MySqlDataAdapter adapter = new MySqlDataAdapter();
    adapter.SelectCommand = cmd;

    DataTable dt = new DataTable();
    adapter.Fill(dt);

    conn.Close();

    return dt;
}

Two Types of LinQ Syntax

class LinQ
{
  int[] numbers = { 5, 10, 8, 3, 6, 12};


 
  //METHOD SYNTAX   
  IEnumerable<int> numQuery = numbers.Where(n => (n%2==0)).OrderBy(n==>n);  

 
  //QUERY SYNTAX   
  IEnumerable<int> numQuery = from n in numbers               
                  where n%2 == 0
                  order by n
                  select n;
}

WPF: Basic Thread

using System.Windows.Threading;
using System.Threading;

private void btnPlay01_Click(object sender, RoutedEventArgs e)
{
    ThreadStart start1 = new ThreadStart(Thread1);
    Thread t1 = new Thread(start1);
    t1.Start();
}

public void Thread1()
{
    int x = 0;
    do
    {
      x++;
      Thread.Sleep(100);
      Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
      {
        lbl01.Content = String.Format("Thread 1 running: {0}", x);
      }));
    }while (x < 50);
}