There are a number of useful properties of thread class. Once a thread is created, it can be assigned some properties by which it can be easy to handle this thread.
Thread.Name
This is a property by which we can assign the name to a thread. This is of great benefit in debugging. There is one thing to remember about this property that a thread can be named only once in its lifetime. An action to name an already named thread would result in an exception.
Thread worker = new Thread(Job); //where "Job" is the name of a function
worker.Name = "Worker Thread";
The application’s main thread can also be assigned a name –
static void main() {
Thread.CurrentThread.Name = "parent Tthread";
Thread worker = new Thread (Job);
worker.Name = "worker thread";
worker.Start();
Job();
}
static void Job() {
Console.WriteLine ("Hello from " + Thread.CurrentThread.Name);
}
Output:
Hello from worker thread
Hello from parent thread
Thread.Priority
Priority is the measure of execution time a thread will get in comparison to the other threds in the same process.
Various values of thread priority can be:
Lowest, BelowNormal, Normal, AboveNormal, Highest
Inorder to increase the priority of a thread in real terms we need to increase the priority of the process too in which the thread exists.
This is achieved in the following way:
Process.CurrentProcess().PriorityClass = ProcessPriorityClass.High.
By increasing the priority of the process, we are ultimately incresing the chances of execution of the threads in that process thus increasing the thread's proirity in real terms.
Thus increasing the thread's priority increase it chances of execution more than compared to other threads in the same process or a process of lower priority.
Thread.IsBackground
A backgrond thread is a one that will end when the Foreground threads attached with it will end. In C#, all the threads are foreround threads by default.
To change a thread to a background thread:
Thread worker= new Thread(Job);
worker.IsBackgound = true;
This will make the worker thread a background thread and will force the worker thread to abort when the main thread will exit and all the foregound threads are completed.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment