Search This Blog

Tuesday, January 26, 2010

C# Threading - Wait Handles

Wait handles are suitable for signaling a waiting worker thread to begin a task from where it is paused. This is obviously done cross threads(also capable of cross process), means that we can signal from main thread to the worker thread to start its execution from the place where the worked thread paused its execution.

This is done through a construct called as "WaitHandle". WaitHandle is implemented via class named "EventWaitHanlde".

The syntax for creating EventWaitHanlde is the following:
EventWaitHanlde ewh = new EventWaitHanlde(false, EventResetMode.Auto);

The above parameters for the EventWaitHandle are the ones that would be used in most of the cases. The first parameter "false" states not to start the execution atonce but wait for the signal. EventResetMode.Auto means that only one request will be executed for one signal.

class clsTestWaitHandle
{
static EventWaitHandle ewh = new EventWaitHandle(false,EventResetMode.Auto);
static void Main()
{
new Thread (Job).Start();
Console.WriteLine ("Main Thread executing...");
Console.WriteLine ("Main Thread now going to notify the worker thread...");
wh.Set(); // wake up the worker thread
}
static void Job()
{
Console.WriteLine ("Worker Thread Started...");
Console.WriteLine ("Worker Thread will start waiting now...");
ewh.WaitOne(); // Wait for the notification
Console.WriteLine ("Worker thread Notified and resumes execution");
}
}

OUTPUT:
Worker Thread Started...
Worker Thread will start waiting now...
Main Thread executing...
Main Thread now going to notify the worker thread...
Worker thread Notified and resumes execution

The WaitHanlde as said earlier can be cross process also. This is done by giving name to the EventWaitHandle object. If the name is already in use on the computer by some other EventWaitHandle object, reference to the same underlying EventWaitHandle will be created, otherwise the operating system creates a new one.

Here's an example:
EventWaitHandle ewh = new EventWaitHandle (false, EventResetMode.Auto,
"OrganizationName.ProjectName");
If two applications each ran this code, they would be able to signal each other: the wait handle would work across all threads in both processes.

Monday, January 25, 2010

C# Threading - Locks and Synchronization

Thread Safety is a concept that is much too heard and least implemented by developers. Locking basically enforces access rules and that also exclusive access. Locking ensures that only one thread can enter particular sections of code at a time.

class clsTestUnsafeClass
{
static bool bln = true;

static void Job()
{
if (bln)
{
Console.WriteLine ("bln will be false now");
bln = false;
}
}
}

The above code is not thread safe because if Job is called by two threads simultaneously it would be possible that both threads write "bln will be false now".
This is because it could be that one thread has validated the condition bln = true and has written on the console and before it sets bln=false, the time slice for this thread finishes and a new thread enters the if(bln) loop. Since previous thread has not yet set bln=false, the new thread can easily enter the condition and will also write "bln will be false now". Thus both the threads have written the same line although it was not intended.

Inorder to avoid this, we use locking mechanism:

class clsTestThreadsafeClass
{
static bool bln = true;
staic object dummyobject = new object();
static void Job()
{
lock(dummyobject)
{
if (bln)
{
Console.WriteLine ("bln will be false now");
bln = false;
}
}
}
}

The above code will lock the fragment of code after the lock statement for one thread. This means that if one thread has entered a lock block and its time slice has finished, even if a new thread reaches the lock block, it will be denied entry into the lock block till it is freed by the old thread which has entered first into the lock block. Thus the second thread will be blocked outside the code block till the first thread completes execution in the block and thus there will be no uintentional code effects due to time slicing.

C# Threading - Thread Properties

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.

Friday, January 22, 2010

C# Threading / MultiThreading - Exception Handling

Once a thread starts executing, all the Try-catch blocks in scope when was thread is created are of no relevance. So inorder to catch an exception, we have to catch it in the thread method itself.
Consider the example below:

public static void Main()
{
try
{
Thread worker = new Thread (Job);
worker.Start();
}
catch (Exception ex)
{
// THIS WILL NEVER EXECUTE
Console.WriteLine ("Exception occured");
}

static void Job()
{
throw new Exception();
}

}

In the above snippet, the function "Job" in worker thread throws an exception. But since there is no try catch in the the "Job" function, thus this exception will not be handled.

Inorder to handle this exception, we will need to add try catch to the "Job" function:

public static void Main()
{
try
{
Thread worker = new Thread (Job);
worker.Start();
}
catch (Exception ex)
{
// THIS WILL NEVER EXECUTE
Console.WriteLine ("Exception occured");
}

static void Job()
{
try
{
throw new Exception();
}
catch(Exception ex)
{
Console.WriteLine("Exception will be handled now");
}
}

}

Points to keep in Mind:
1. Global Exception Handler used in windows forms like
Application.ThreadException += LogError;
will not be able to catch exceptions when the exceptions occur in a thread method not wrapped in its try catch block.

2. AppDomain.UnhandledException event handler provided by Windows forms will be able to log the error but not help us in saving from getting the application down with error if exceptions occur in a thread method not wrapped in its try catch block.

C# Theading / Multi-Threading

This is really a hot topic now a days. This topic struck me when i was caught with a surprise call from a consultant and he wanted to me to rate myself from 1 to 10 in Threading. O, I was amazed..before that i used to ask poeple while conducting interviews to rate themselves in c#, vb.net, sql server, javascript. But to rate in a concept from 1 to 10 was astonishing to me and also on a topic which is mostly little bit known...so i have put in some good effort in it now and waiting for a call from the same consultant and try to be a confident guy now...


Threading/Multi-Threading:

Threading basically is a concept to make parallel execution a possibility. A thread is actually a unit of processor time consumption, means to say that a thread is something to which processor time is given. A process can contain different threads but the processor time is not given to processes but it is gifted only to threads inside them.
Multi-threading is probably one of the worst understood aspects of programming but in today's era, every programmer needs to know good bit of it to write an efficient application.

Lets write a simple threading program:

using System;
using System.Threading;

public class TestThreading
{
static void Main()
{
Thread worker = new Thread(Job);
worker.Start();

for (int i=0; i < 5; i++)
{
Console.WriteLine ("Main thread: {0}", i);
Thread.Sleep(1000);
}
}

static void Job()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("worker thread: {0}", i);
Thread.Sleep(500);
}
}
}


OUTPUT:
Main thread: 0
Worker thread: 0
Worker thread: 1
Main thread: 1
Worker thread: 2
Worker thread: 3
Main thread: 2
Worker thread: 4
Worker thread: 5
Main thread: 3
Worker thread: 6
Worker thread: 7
Main thread: 4
Worker thread: 8
Worker thread: 9

We can see from the above output that there are two threads running actually, sometimes main thread and other times worker thread. The output in the above is random and the next time the progream may well give output in a different order.

Creation of the new Thread is done here:
Thread worker = new Thread(Job);

We can also write the above line in the following way:
Thread worker = new Thread(new ThreadStart(Job));

Pass parameters to Functions in Threads:
In C# 2.0, MS introduced the concept of parameterized threads which have the ability of passing parameters to the function which will be called by new thread.

Parmeterize thread can be created in the following way:

Thread worker = new Thread(new ParameterizedThreadStart(JobWithParamter));
worker.Start("Parametrized");

static void JobWithParameter(object parameter)
{
Console.WriteLine("worker thread: {0}", parameter.ToString());
}

Thus inorder to pass parameters to thread function, we are to pass parameter while calling 'Start'. This is to note that the parameter can only be an object type and nothing else.

Different Scenarios:
Scenario 1 --> We want to pass more than one parameters:
We can achieve this by creating a class with the desired number of fields which we want to pass as arguments to thread function and then passing that class's object into the 'Start'.


class Employee
{
string name;
int salary;
}

class abc
{
static void main()
{
Employee employee = new Employee(){name="gj";salary=50000};

Thread worker = new Thread(JobWithParamters);
worker.Start(employee);
}

static void JobWithParameters(object parameter)
{
Employee employee = (Employee)parameter;
Console.WriteLine("Employee Name: {0}", employee.name);
Console.WriteLine("Employee Salary: {0}", employee.salary.ToString());
}
}

Scenario 2: We need to pass the parameters without creating a new class:
I this scenario, we can create anonymous functions and thus pass any number of arguments.

class abc
{
static void main()
{

Thread worker = new Thread(new delegate() {JobWithActualParameters("Gj", 50000);});
worker.Start(employee);
}

static void JobWithActualParameters(string name, int salary)
{
Console.WriteLine("Employee Name: {0}", name);
Console.WriteLine("Employee Salary: {0}", salary.ToString());
}
}


We will cover handling Exceptions in Threading in our next article