Multithreading basics in .Net Framework
Published: 04 Feb 2003 15:14 GMT

In fact, almost any programmer can delve into it and master the fundamentals. I'll introduce you to the basics of multithreaded programming and provide some sample code you can use to start experimenting.
Creating threads
To get multithreaded programming running, you must first create an instance of a Thread. You don't have much in the way of options, as there is only one constructor:
Visual Basic
Public Sub New( ByVal start As ThreadStart )
C#
public Thread( ThreadStart start );
C++
public: Thread(ThreadStart* start );
The parameter ThreadStart is a delegate to the method that is the starting point of the thread. The signature of the delegate is a method with no parameters and returns nothing, as demonstrated below:
Visual Basic
Public Delegate Sub ThreadStart()
C#
public delegate void ThreadStart();
C++
public __gc __delegate void ThreadStart();
Starting threads
One thing that may not be obvious when you first start working with threads is that creating an instance of the Thread object does not cause the thread to start. To get the thread to start, you need to call the Thread class's Start() method, like this:
Visual Basic
Public Sub Start()
C#
public void Start();
C++
public: void Start();
Getting a thread to sleep
When developing a thread, you may find that you don't need it to continually run, or you might want to delay the thread while some other thread runs. To handle this, you could place a delay loop like a "do-nothing" for-loop. But that would waste CPU cycles. Instead, you should temporarily stop the thread or put it to sleep.
Doing this couldn't be easier. Simply add the following static/shared Sleep() method:
Visual Basic
Overloads Public Shared Sub Sleep(Integer)
C#
public static void Sleep(int);
C++
public: static void Sleep(Int32);
This line causes the current thread to go to sleep for the interval specified either in an integer value of milliseconds, as the examples above show, or using a TimeSpan structure.
The Sleep() method also takes two special values: Infinite, which means sleep forever, and 0, meaning give up the rest of the thread's current CPU time slice.
A neat thing to remember is that the main function is also a thread. This means you can use Sleep() to make any application sleep.






