VC++ MVP 2006, C# MVP 2007 Ravi Bhavnani's .NET bits
A compendium of scribblings, hacks, and things .NET

Linkworthy
  • The CodeProject
  • CodePlex
  • Channel 9
  • The Lab with Leo Laporte
  •  
    Thread parameters - the .NET 2.0 way
    More manageable managed multithreading
    by Ravi Bhavnani, 12 Nov 2007
    Home  All articles

    One of the useful niblets in .NET 2.0 is the new ParameterizedThreadStart delegate that makes it convenient to pass parameters (OK, a single parameter - but it's an Object so you can pretty much pass anything you want!) to a thread.  ParameterizedThreadStart makes your multithreaded code more readable and therefore easier to maintain.

    In the "old" days, I had to expose an explicit property in the class that performed a multithreaded task like so:

      1   // An object that compresses the contents of a folder to
      2   // a .ZIP file.
      3   public class FolderCompresser
      4   {
      5     // The folder to be compressed to a .ZIP file
      6     public string Folder {
      7       get { return _folder; }
      8       set { _folder = value; }
      9     }
     10 
     11     // The compress method
     12     public void Compress()
     13     {
     14       string zipFilename = _folder + ".zip";
     15       internalCompress (_folder, zipFilename);
     16     }
     17   }

    The client code that used FolderCompresser had to explicitly set its parameter before starting the thread:

      1   // Invoke the compressor
      2   FolderCompressor fc = new FolderCompressor();
      3   fc.Folder = @"C:\MyFolder";
      4   Thread compressThread =
      5     Thread (new ThreadStart (fc.Compress));
      6   compressThread.Start();

    ParameterizedThreadStart lets you specify the thread's parameter when you start the thread, thereby allowing you to move the object's processing to a static method, like so:

      1   // An object that compresses the contents of a folder to
      2   // a .ZIP file.
      3   public class FolderCompresser
      4   {
      5     // The compress method
      6     public static void Compress
      7       (Object o)
      8     {
      9       string folder = o as string;
     10       string zipFilename = folder + ".zip";
     11       internalCompress (folder, zipFilename);
     12     }
     13   }

    The client code that uses FolderCompressor is reduced to:

      1   Thread compressThread =
      2     new Thread (new ParameterizedThreadStart
      3                  (FolderCompresser.Compress));
      4   compressThread.Start (@"C:\MyFolder");

    And there you have it - a useful helper class to make your managed multithreaded code more manageable.

     

    Most of the drivel at this site is copyright Ravi Bhavnani.
    Questions or comments?  Send mail to ravib@ravib.com