ThreadStart

In terms of implementation, let me explain the details of coding statement and its significance.  A thread does not begin executing when it is created in C# program as follows:

    Thread thread = new Thread(job)

In fact, thread execution is scheduled by calling the C# Start method as follows:

    thread.Start();

To sequence .NET thread processing, ThreadStart delegate is a parameter when creating a new thread instance:

    ThreadStart job = new ThreadStart(ThreadJob);

Generally, worker thread is referred to describe another thread from the one that is doing the work on the current thread, which, in lots of cases, is a foreground or UI thread.
It is similar to master slave execution model in computing theory.  With these fundamental coding concepts, simple thread program is written with main and worker thread as follows:

    /// <summary>
/// Main method to kick start Job
/// </summary>
public static void Main()
{
ThreadStart job = new ThreadStart(ThreadJob);
Thread thread = new Thread(job);
thread.Start();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Main thread: {0}", i);
Thread.Sleep(1000);
}
Console.ReadKey();
}

/// <summary>
/// Sub or worker thread is getting triggered here
/// </summary>
static void ThreadJob()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Worker thread: {0}", i);
Thread.Sleep(500);
}
}

In terms of execution of the preceding code, worker thread counts from 0 to 9 fairly fast (about twice a second) while the main thread counts from 0 to 4 fairly slowly (about once a second). In turn, framework execution has discrepancy of execution between main thread of 1000ms sleep and worker thread of 500ms. As a result, the execution output on one machine looks like the following screenshot:

On observing the code execution's result, it is clear indication that the sleeping thread will immediately start running across main and worker threads as soon as the sleep finishes. On thread execution, another thread may be currently running coincidentally on a single processor machine. The impact is that the current thread needs to await until the system thread scheduler shares the processor time during the next round of allocation.

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

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