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:
-
-
/// <summary>
-
/// Cleans up images from the settings directory based on image type and timeout period.
-
/// </summary>
-
/// <param>ChartHttpHandler.StorageSettings as an object – for multi-threading purposes.</param>
-
public static void ImageCleanup(object objSetting)
-
-
{
-
// retrieve the settings object – could be any object type
-
ChartHttpHandler.StorageSettings settings = objSetting as ChartHttpHandler.StorageSettings;
-
// TODO: complete actions
-
}
-
To spawn the method on a thread:
-
-
/// <summary>
-
/// Test method for spawning above.
-
/// </summary>
-
public void TestThread()
-
{
-
// define the settings object
-
// start a new thread to cleanup the files. Pass in a possible variable – or pass nothing (be sure to remove from signature above).
-
new Thread(ImageCleanup).Start(settings);
-
}
-