Multithreading with C#

This tutorial offers an introduction to multithreading in C# and it also uses a sample project to show you how to start using threads.

Context Ads

More C# Resources


Okay, where to start… ah yes the beginning, Multithreading is essentially the same principal as a production line in a factory each thread is a worker designated to carry out a simplistic task before the work moves on, its helpful to think about multi-threading in this way because as much as it is a good thing, it can also be counterproductive in very small projects that do not need more than one worker as it were or it can be very useful for a large application such as OCR working with 4 workers over a 20x20pixel area is more efficient than having one worker doing everything!

It takes all kinds of workers to make up a simple 3D game! Firstly you have the time, then the graphics, the lighting, the sound, the input, the AI, the networking etc… Our example will be much more simple than that and will be broken down and explored for yourselves to add to your knowledge.

Start the new project in Visual Studio, SharpDevelop or whatever you want.

Append the namespace System.Threading to the main source file:

using System.Threading;

At the bottom of the Main() in your application type:

MainForm mainForm = new MainForm();

for(int i=0; i<5; i++){
Thread backgroundThread = new Thread(new ThreadStart(mainForm.doSomething));

Now this sets up for 5 seperate workers to be created from within the class MainForm which is a partial class derived from the default windows form class, using this method you could save using a different thread in an applicationso that you could use the main application regardless of system overheads when saving the content data (by the way, we are not doing that here).

Go inside the MainForm Class and paste the following

public void doSomething()



    return ;

This will be the code executed in the different threads much like creating instances so this method of multithreading is useful for instancing or creating copied data from a template.

Press the Run or F5 in Visual Studio and watch your creation fly.

Troubleshooting Threads

Synchronising Threads
To synchronise threads you can use the System.Threading.Interlocked class this is for use when threads all use a single peice of data like in a FPS game most of the threads would have to be interlocked to prevent sync / lag between seperate threads.

Thread Errors Due to Exceptions

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
This will stop most exceptions generated from multithreading over a single control (for a webserver, etc.)

I hope this has been an eye opener for you all and until my next tut have fun! 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top