Friday, November 9, 2007

C# threading example

This is a simple, but handy multi-thread example. The two "foreach" sections at the end is where the hip happens. All process' will start at the same time and "Main" will not exit until all threads have been joined.

static void Main(string[] args)
{
  ArrayList threads = new ArrayList();

  try
  {
    if(args.Length > 0)
  {

  switch(args[0].ToUpper())
  {
    case "case1" :
    {
      case1Export case1 = new case1Export();
      Thread t1 = new Thread(new ThreadStart(case1.Start));
      threads.Add(t1);
      break;
    }
    case "case2" :
    {
      case2Export case2 = new case2Export();
      Thread t2 = new Thread(new ThreadStart(case2.Start));
      threads.Add(t2);
      break;
    }
    case "case3" :
    {
      case3Export case3 = new case3Export();
      Thread t3 = new Thread(new ThreadStart(case3.Start));
      threads.Add(t3);
      break;
    }
    default :
      break;
    }
  }

  foreach(Thread thread in threads)
  {
    thread.Start();
  }

  foreach(Thread joinThread in threads)
  {
    joinThread.Join();
  }
}

No comments: