Quick Multi-Threading Example

In the past I often looked at Multi-Threading as requiring more time to take advantage of. Recently, I took advantage of multi-threading in its generic form (not using strongly typed classes inheriting from the Thread). I found myself in a situation where I wanted to spawn a separate action and let it run without interfering with the current thread. To my surprise it was quite easy to do with getting into new classes, etc.

In this example, a new thread is spawned to cleanup some images on the file system, in which the current process doesn’t care about:

The Method we want to multi thread:

  1.  
  2. /// <summary>
  3. /// Cleans up images from the settings directory based on image type and timeout period.
  4. /// </summary>
  5. /// <param>ChartHttpHandler.StorageSettings as an object – for multi-threading purposes.</param>
  6. public static void ImageCleanup(object objSetting)
  7.  
  8. {
  9.                 // retrieve the settings object – could be any object type
  10.                 ChartHttpHandler.StorageSettings settings = objSetting as ChartHttpHandler.StorageSettings;
  11.                 // TODO: complete actions
  12. }
  13.  

To spawn the method on a thread:

  1.  
  2. /// <summary>
  3. /// Test method for spawning above.
  4. /// </summary>
  5. public void TestThread()
  6. {
  7.                 // define the settings object
  8.                // start a new thread to cleanup the files. Pass in a possible variable – or pass nothing (be sure to remove from signature above).
  9.               new Thread(ImageCleanup).Start(settings);
  10. }
  11.  

Leave a Reply