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. // retrieve the settings object – could be any object type
  7. // TODO: complete actions
  8. }
  9.  

To spawn the method on a thread:

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