StartingThreads.cs, StartingThreads.txt,


/////////////////////////////////////////////////////////////////////
// StartingThreads.cs - demo of thread delegates                   //
//                                                                 //
// Jim Fawcett, CSE681 - Software Modeling and Analysis, Summer 09 //
/////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace StartingThreads
{
  class DemoThreads
  {
    string msg_ = null;
    DemoThreads(string msg) { msg_ = msg; }

    public void newMessage(string msg) { msg_ = msg; }

    void ThreadProc()  // ThreadStart delegate accepts this signature
    {
      MsgProc(msg_);
    }

    void MsgProc(string msg)
    {
      Console.Write("\n  {0}", msg as string);
    }

    void ObjProc(object msg)  // ParameterizedThreadStart accepts this signature
    {
      Console.Write("\n  {0}", msg as string);
    }

    static void Main(string[] args)
    {
      int count = 0;

      // Explicit use of ThreadStart delegate
      DemoThreads p = new DemoThreads(String.Format("message #{0}", ++count));
      ThreadStart ts = new ThreadStart(p.ThreadProc);
      Thread t1 = new Thread(ts);
      t1.Start();
      t1.Join();  // if you remove this you may not see message #1 
                  // due to race condition with next statement, below.

      // Implicit use of ThreadStart delegate uses type inference
      p.newMessage(String.Format("message #{0}", ++count));
      Thread t1b = new Thread(p.ThreadProc);
      t1b.Start();

      // Explicit use of ParameterizedThreadStart delegate
      ParameterizedThreadStart pts = new ParameterizedThreadStart(p.ObjProc);
      Thread t2 = new Thread(pts);
      t2.Start(String.Format("message #{0}", ++count));

      // Implicit use of ParameterizedThreadStart delegate via type inference
      Thread t2b = new Thread(p.ObjProc);
      t2b.Start(String.Format("message #{0}", ++count));

      //////////////////////////////////
      // This doesn't work:
      //Action<string> starter = new Action<string>(p.MsgProc);
      //Thread t3 = new Thread(starter);
      //t3.Join();

      // Implicit use of ParameterizedThreadStart via type inference
      Thread t2c = new Thread((msg) => p.ObjProc(msg));
      t2c.Start(String.Format("message #{0}", ++count));

      t1.Join();
      t1b.Join();
      t2.Join();
      t2b.Join();
      t2c.Join();

      Console.Write("\n\n");
    }
  }
}