Sunday, 15 September 2013

C# ParameterizedThreadStart

ParameterizedThreadStart starts a thread with an argument. It is instantiated with a target method. We can then pass this instance to the Thread constructor. The target method is then invoked upon starting the Thread.

Example

As an overview, this program creates an array of four threads, creates ParameterizedThreadStarts for them, then starts them and joins them. The static Start method is executed four different times on separate threads.
With ParameterizedThreadStart, you pass a function name as the argument. This is an object type that you can later cast. When calling the Thread Start method, you must pass an argument.
Program that uses ParameterizedThreadStart: C#

using System;
using System.Threading;

class Program
{
    static void Main()
    {
 // Create an array of Thread references.
 Thread[] array = new Thread[4];
 for (int i = 0; i < array.Length; i++)
 {
     // Start the thread with a ParameterizedThreadStart.
     ParameterizedThreadStart start = new ParameterizedThreadStart(Start);
     array[i] = new Thread(start);
     array[i].Start(i);
 }
 // Join all the threads.
 for (int i = 0; i < array.Length; i++)
 {
     array[i].Join();
 }
 Console.WriteLine("DONE");
    }

    static void Start(object info)
    {
 // This receives the value passed into the Thread.Start method.
 int value = (int)info;
 Console.WriteLine(value);
    }
}

Output

1
0
2
3
DONE

Order of thread execution. You can see that in this example the threads were called in a non-sequential order. This is because there is some indeterminate pause before the operating system and framework can receive a thread, and by that time we may have already requested another thread.
Note: You can't count on the order of execution exactly here.

No parameters?


What if you want to start a thread but don't need to pass any parameters to it? You don't need to pass the null literal. You can instead use the ThreadStart type, which fortunately is detailed also on this site.
Note: Please visit the more specific article.
ThreadStart Use

Summary

The ParameterizedThreadStart type gives you the ability to pass an argument of any type to a specific method on a thread in the C# language. This functionality enables you to process many different data values on different threads, improving performance and runtime in your C# program.
Thread Join Method

No comments:

Post a Comment