C# Delegates and Events—Thread delegates

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

C# Delegates and Events

edit

Thread delegates

Multithreaded programming in .NET is implemented through the use of delegates. The .NET Framework defines the ThreadStart delegate to invoke a method in a separate thread. The Thread class, defined in the System.Threading namespace, accepts an instance of the ThreadStart delegate as its constructor argument. When you call the Thread object’s Start method, that Thread object will invoke the delegate in its own thread of execution. The following example demonstrates this by calling a method named ThreadProc in a separate thread.

static void ThreadProc() {
   // do some thread work
   CalculatePrimes();
   }
 
static void Main(string[] args) {
   Thread t = new Thread(new ThreadStart(ThreadProc));
   t.Start();
   t.Join();
   }

In this example, the Main method creates a Thread object, passing a new ThreadStart delegate to its constructor. That ThreadStart delegate stores a reference to the ThreadProc method. Then, Main calls the Thread object’s Start method which causes its delegate to begin execution in a separate thread. The final line of Main is a call to the Thread object’s Join method, which causes Main to block, waiting for the thread’s delegated method call to return.


Previous_Page_.gif Next_Page_.gif


Personal tools