Threading in CSharp – A Step Ahead Series

Scope
Scope of this article is upto its title and subsequent reference of A Step Ahead Series

Threading in CSharp – A Step Ahead Series

Multi-Threading

In Software this is not a new concept. Multithreading forms a subset of multitasking. Instead of having switch between programs this feature switches between different parts of the same program. For example when you are writing words in Ms-word then spell checking is going on background.

Threads
Simply, thread is the basic unit having processor tie, allocated by operating system. A thread can be defined as a separate path of execution for a program.

1. Starting Thread
Object thread is obtained from System.Threading namespace. With the use object of this class we can create a new thread, delete, pause, and resume threads. Simple a new thread is created by Thread class and started by Thread.Start().
eg. Thread th = new Thread (new ThreadStart (somedata));
th.Start();

2. Pausing Thread
Some time the requirement to pause a thread for certain time of interval; you can attain the same by using Sleep (n) method. This method takes an integer value to determine how long a thread should pause or Sleep.
eg. th.Sleep(2000);

Note:
To pause or sleep a thread for an in determine time, just call the sleep () method as: [make sure you have added System.Threading namespace] Thread.Sleep(TimeOut.Infinite).
To Resume or interrupt this call : Thread.Interrupt () method.

3. Suspending Thread
Of course, there is a Suspend () method which suspends the thread. It is suspended until a Resume () method called.

eg. if (th.ThreadState = = ThreadState.Running)
th.Suspended();


4. Resuming Thread
To Resume a suspended thread, there is a Resume () method, thread resumes if earlier suspended if not so then there is no effect of Resume () method on the thread.

eg. if (th.ThreadState = = ThreadState.Suspended)
th.Resume();

5. Killing Thread
You can call Abort () method to kill a thread, before calling the same method, make sure thread is alive.

eg. if (th.IsAlive)
th.Abort();

Suspend and Resume in Threading
It is similar to sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume ().The difference between sleep and suspend is that the later does no immediately place a thread in the wait state. The thread does not suspend until the .Net runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

Important:
You can change thread priority for that just supply : th.Priority = ThreadPriority.Highest. [th – Thread name]. Priority sets the sequence of thread in which they are running. You can set the following priority to thread(s):

1. ThreadPriority.Highest
2. ThreadPriority.AboveNormal
3. ThreadPriority.Normal
4. ThreadPriority.BelowNormal
5. ThreadPriority.Lowest

Join () Method in threading
There are two version of this method: Thread.Join () and Thread.Join (n): n- Integer, it returns a Boolean value.

It is very much important to know whether threads operation depends upon threads suppose one thread returns some value and another thread uses these values in that condition it is important to know whether first thread has completed. The Thread.Join () method determine that whether a thread has completed before starting another thread.

Thread.Join () method waits a specified amount of time for a thread to end. If the thread ends before time-out, it returns true otherwise it returns false.

Example:
If you have two threads th1 and th2 and calls th2.Join () in the execution of th1, it means th1 waits until th2 ends.

In the other hand Thread.Join (n) takes integer value which specified wait time, if within specified time thread does not end then the waiting thread will start.

For Code snippet please refer: Threading in C# - Easier to write .

Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.

How to Implement Synchronization
There are certain situations that you need to be careful with when using threads. If two threads; a main and any other worker thread try to access the same variable at the same time, you will have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock the variable before accessing it. However, if two threads lock the same variable at the same time, you will have a deadlock problem.

Example:
lock (x)
{
//Write something for x
}

Note:
• It is possible to use events with threading; it’s a technique to synchronize one thread to another.
• A deadlock is a bug that can occur when two threads have to access resources that are locked by the other.

The monitor Object
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished.

Features of monitor object
• Is associated with an object on demand.
• Can be called directly from any context.
• Can not be instantiated.

Some monitor method(s)

1. Monitor.Enter Method
It obtains the monitor lock for an object. This method will block if another thread holds the lock. It will not block if the current thread holds the lock.

eg. public static void Enter (object obj);

2. Monitor.TryEnter Method
It is similar to Enter method but it never block or will only block for a certain amount of time.

3. Monitor.Exit Method
It releases the Monitor lock if one or more threads are waiting to acquire the lock, and the current thread has executed Exit as many times as it has executed Enter, one of the threads will be unblocked and allowed to proceed.

eg. static void Exit (object obj);

4. Monitor.Wait Method
It waits for notification passed by the CLR from the object [through Pulse or PulseaAll methods]. The wait method must be invoked from within a synchronized block of code.

This method aquires monitor waithandler for the object. If this thread holds the monitor lock for the object, it releases it. On exiting from the method, it contains the monitor lock back.

Note :
Wait handles sends signal of a thread status from one thread to another thread. Three are three kinds of wait mode(s): 1. WaitOne 2. WaitAny 3. Wait All

When a thread wants to release a Wait handle it can call Set method. You can use Mutex [mutually exclusive] objects to avail for the modes. Mutex objects are synchronization objects that can only be created by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, otherreads must wait for ownership of a mutex object before using the resource.The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to be signaled and the next waiting thread gets ownership.

5. Monitor.Pulse Method
It notifies a thread in the waiting queue of a change in the object’s state.
eg. Public static void Pulse (object obj);

6. Monitor.PulseAll Method
It sends a notification to al waiting objects.
eg. public static void PulseAll (object obj);

A subsequent example is available at Thread Monitoring in CSharp Easier to Write .

This is not a full sort-of article but I try to my best to cover every topic from ancient to current language scenarios.


Article by Gaurav Aroraa
Gaurav is a Microsoft Technology Specialist professional. He has awarded lifetime membership from Computer Society of India (CSI). He has more than 13yrs of experience in the industry. Currently, he is working in the capacity of Solution Architect with an MNC. He is serving to the various communities since 1999.

Follow Gaurav Aroraa or read 157 articles authored by Gaurav Aroraa

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: