Parameterized threads

Here, we will look at how we can pass arguments to the ThreadStart method. To achieve this, we will be using the ParameterizedThreadStart delegate on the constructor. The signature of this delegate is as follows:

public delegate void ParameterizedThreadStart(object obj)

When you pass a parameter as an object to the ThreadStart method, it will cast the parameter to the appropriate type. The following sample program uses the same logic that we used previously, except that we pass the interval as an argument via the ThreadStart method:

 public static void ParameterizedThread()
{
var th = new Thread(ThreadThree);
th.Start(3000);
Thread.Sleep(1000);
Console.WriteLine("Primary thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId);
}

private static void ThreadThree(object obj)
{
int interval = Convert.ToInt32(obj);
var sw = Stopwatch.StartNew();
Console.WriteLine("ThreadTwo Id: {0} ThreadThree state: {1}, ThreadThree Priority: {2}",
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.ThreadState,
Thread.CurrentThread.Priority);
do
{
Console.WriteLine("ThreadThree Id: {0}, ThreadThree elapsed time {1:N2} seconds",
Thread.CurrentThread.ManagedThreadId,
sw.ElapsedMilliseconds / 1000.0);
Thread.Sleep(500);
} while (sw.ElapsedMilliseconds <= interval);
sw.Stop();
}

The following screenshot shows the output of the preceding code:

Now, let's look at foreground and background threads.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.234.150