Thread properties

Each thread carries certain properties. The following table details each of them:

IsAlive Returns true if the thread is in a started state.
IsBackground Gets or sets this property to let the system know how to execute the thread.
Name Name of the thread.
Priority Gets or sets thread priority. The default is Normal.
ThreadState Gets the thread's current state.

 

In the following code sample, we will call a method that will display information about some thread properties. We will also understand how we can pause a thread and terminate it:

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

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

When you execute the program, you will see the properties of each thread. You will also observe that although the primary thread has completed, the worker threads are still executing:

You might have observed that only one thread is writing to the console at a time. This is known as synchronization. In this case, it is handled by the console class for us. Synchronization allows no two threads to execute the same code block at the same time.

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

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