Subscribe

RSS Feed (xml)

Execute a Method Using a New Thread

For maximum control and flexibility when creating multithreaded applications, you need to take a direct role in the creation and management of threads. This is the most complex approach to multithreaded programming, but it's the only way to overcome the restrictions and limitations inherent in the approaches using thread-pool threads, as discussed in the four preceding recipes. The Thread class provides the mechanism through which you create and control threads. To create and start a new thread, follow this process:



  1. Create a ThreadStart delegate instance that references the method that contains the code you want the new thread to run. As with any delegate, ThreadStart can reference a static method or an instance method. The referenced method must take no arguments and return void.



  2. Create a new Thread object, and pass the ThreadStart delegate instance as an argument to the Thread constructor. The new thread has an initial state of Unstarted (a member of the System.Threading.ThreadState enumeration).



  3. Call Start on the Thread object, which changes its state to ThreadState.Running and begins execution of the method referenced by the ThreadStart delegate instance. (If you call Start more than once, it will throw a System.Threading.ThreadStateException.)
Because the ThreadStart delegate declares no arguments, you can't pass data directly to the referenced method. To pass data to a new thread, you must configure the data such that it's accessible to the code running in the new thread. The most common approach is to declare a class that encapsulates both the data required by the thread and the method executed by the thread. When you want to start a new thread, create an instance of the container object, configure its state, and then start the new thread. Here is an example.
using System;
using System.Threading;

public class ThreadExample {

    // Private member variables hold state for use by the new thread.
    private int iterations;
    private string message;
    private int delay;

    public ThreadExample(int iterations, string message, int delay) {

        this.iterations = iterations;
        this.message = message;
        this.delay = delay;
    }

    public void Start() {

        // Create a ThreadStart delegate instance that references
        // DisplayMessage.
        ThreadStart method = new ThreadStart(this.DisplayMessage);

        // Create a new Thread object and pass the ThreadStart
        // delegate instance to its constructor.
        Thread thread = new Thread(method);

        Console.WriteLine("{0} : Starting new thread.",  
            DateTime.Now.ToString("HH:mm:ss.ffff"));

        // Start the new thread.
        thread.Start();
    }

    private void DisplayMessage() {

        // Display the message to the console the specified number of 
        // times, sleeping between each message for the specified duration.
        for (int count = 0; count < iterations; count++) {

            Console.WriteLine("{0} : {1}",  
                DateTime.Now.ToString("HH:mm:ss.ffff"), message);

            // Sleep for the specified period.
            Thread.Sleep(delay);
        }
    }

    public static void Main() {

        // Create a new ThreadExample object.
        ThreadExample example = 
            new ThreadExample(5, "A thread example.", 500);

        // Start the ThreadExample object.
        example.Start();

        // Continue with other processing.
        for (int count = 0; count < 13; count++) {
            Console.WriteLine("{0} : Continue processing...", 
                DateTime.Now.ToString("HH:mm:ss.ffff"));
            Thread.Sleep(200);
        }

        // Wait to continue.
        Console.WriteLine("Main method complete. Press Enter.");
        Console.ReadLine();
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail