|
|
|
|
|
|
|
Technologies:
.NET 1.0/1.1,Visual C# .NET
|
|
Total downloads :
|
|
|
Total page views :
|
21064
|
|
Rating :
|
|
0/5
|
|
This article has been rated :
|
0 times
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
The Complete Visual C# Programmer's Guide, written by the authors of C# Corner, covers most of the major components that make up C# and the .NETenvironment including Windows Forms, ADO.NET, GDI+, Web Services, and Security. The book is geared toward the beginner to intermediate programmers.
|
|
|
|
|
|
|
|
|
|
|
|
|
Summary
Thread basics using followings:
- How to Create thread; use System.Thread() class and create an instance
- How to Join thread; use object.Join() to join threads.
- How to Suspend thread; use object.Sleep(<No of seconds>) to Suspend thread
- How to Kill thread; use object.Abort() to Suspend thread
- Using Interlocked class which uses Increment and decrement method to increment and decrement values.
Thread Synchronization using followings:
- Using Locks: allows to mark a lock on the critical section of the code(program), provides synchronization to an object and then to execute the lock is in effect.
- Using Monitor: allows to decide when to enter and exit the synchronization, and it lets us wait for another area of code to become free. Monitor acts as a smart lock on a resource. When the we need synchronization, we can call the enter() method of the monitor passing the object we want to monitor. We can explicitly choose to wait () method of the monitor to control thread ordering. In case of using wait () waiting threads will be allowed to notified of a chance to run again if the active thread calls Pulse (). This signals the CLR that there has been a chance in the state that might free a thread that is waiting. The CLR tracks of the fact that the earlier thread asked to wait, and the thread will be guaranteed access in the order in which the wait where requested. Exit () can be called once when the thread is finished with the monitor.
Overview

Architecture of CLR
Threading support is in built under Common Language Runtime provided by Microsoft .NET Framework.
Understanding Threading
- Threads are basically light weight processes responsible for multitasking within a single application.
- The base class used for threading is System.Threading
- Threads are managed under the Common Language Runtime, programmers don't have to manage any threads explicitly.
- Using threading with the combination of components it is recommended to use explicit definition and management of the thread.
- Threads are implement when you have situations in which you want to perform more then one task at a time.
- In case of Synchronization. Since you have limited amount of recourses, you may have to restrict the access to the resource to one thread at a time. In this situations you may implement locking on the threading to over come the scenarios.
- An apartment is a logical container within a process and is used for objects that shares the same thread-access requirement. Object in the apartment can all receive method call from any object in any thread in the apartment. And managed object (object created within CLR) are responsible for thread safety.
- Threads can be used under the situation where we must wait for an event such as user input, a read from file, or receipt of data over the network. Freeing the memory to turn it a safe, and it makes our program to appear to run more quickly.
Working with Thread
Create new instance of Thread object. Thread constructor accepts one parameters that is delegate.
MS CLR provides ThreadStart delegate class for starting the thread.
Example:
Thread myThread = new Thread( new ThreadStart(myFunc) );
To run this thread we need following
Thread t1 = new Thread( new ThreadStart(Incrementer) );
To instantiate this we need followings
t1.Start()
Detailed example is as below
namespace Programming_CSharp { using System; using System.Threading; class Tester { static void Main( ) { // make an instance of this class Tester t = new Tester( ); // run outside static Main t.DoTest( ); } public void DoTest( ) { // create a thread for the Incrementer // pass in a ThreadStart delegate // with the address of Incrementer Thread t1 =new Thread(new ThreadStart(Incrementer) ); // create a thread for the Decrementer // pass in a ThreadStart delegate // with the address of Decrementer Thread t2 =new Thread(new ThreadStart(Decrementer) ); // start the threads t1.Start( ); t2.Start( ); } // demo function, counts up to 1K public void Incrementer( ) { for (int i =0;i<1000;i++) { Console.WriteLine("Incrementer: {0}", i); } } // demo function, counts down from 1k public void Decrementer( ) { for (int i = 1000;i>=0;i--) { Console.WriteLine("Decrementer: {0}", i); } } } }
Output:
Incrementer: 102 Incrementer: 103 Incrementer: 104 Incrementer: 105 Incrementer: 106 Decrementer: 1000 Decrementer: 999 Decrementer: 998 Decrementer: 997
Joining Threads
Once thread starts running and in a situation when we need to tell thread to stop processing and wait until a second thread to complete the processing we need to join the 1st thread to the 2nd thread. Use following for the same. This will join the second thread to the 1st.
Example:
t2.Join( )
Suspending Thread
In a situation we some time needs to suspend running thread.
Example:
t2.Sleep(<No of Seconds>)
Killing Thread
Threads has to die after the execution of the process in normal situations, occasionally it is required for the programmer to kill a thread. Threads can be killed using the following.
Example:
t2.Abort()
Advanced Threading
Synchronization
Recollect the discussion we had before in some situations we need to synchronize the running threads, so we can modify the running thread and its resources.
namespace Programming_CSharp { using System; using System.Threading; class Tester { private int counter = 0; static void Main( ) { // make an instance of this class Tester t = new Tester( ); // run outside static Main t.DoTest( ); } public void DoTest( ) { Thread t1 = new Thread( new ThreadStart(Incrementer) ); t1.IsBackground=true; t1.Name = "ThreadOne"; t1.Start( ); Console.WriteLine("Started thread {0}", t1.Name); Thread t2 = new Thread( new ThreadStart(Incrementer) ); t2.IsBackground=true; t2.Name = "ThreadTwo"; t2.Start( ); Console.WriteLine("Started thread {0}", t2.Name); t1.Join( ); t2.Join( ); // after all threads end, print a message Console.WriteLine("All my threads are done."); } // demo function, counts up to 1K public void Incrementer( ) { try { while (counter < 1000) { int temp = counter; temp++; // increment // simulate some work in this method Thread.Sleep(1); // assign the decremented value // and display the results counter = temp; Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name,counter); } } catch (ThreadInterruptedException) { Console.WriteLine("Thread {0} interrupted! Cleaning up...",Thread.CurrentThread.Name); } finally { Console.WriteLine("Thread {0} Exiting. ",Thread.CurrentThread.Name); } } } }
Output:
Started thread ThreadOne Started thread ThreadTwo Thread ThreadOne. Incrementer: 1 Thread ThreadOne. Incrementer: 2 Thread ThreadOne. Incrementer: 3 Thread ThreadTwo. Incrementer: 3 Thread ThreadTwo. Incrementer: 4 Thread ThreadOne. Incrementer: 4 Thread ThreadTwo. Incrementer: 5 Thread ThreadOne. Incrementer: 5 Thread ThreadTwo. Incrementer: 6 Thread ThreadOne. Incrementer: 6
Using Interlock
MS CLR provides synchronization tools and mechanisms. This will allow programmers to place locking over running threads.
VB provides a special class called interlocked just for the reason of locking. This consists of two methods Increment and Decrement.
Example:
public void Incrementer( ) { try { while (counter < 1000) { Interlocked.Increment(ref counter); // simulate some work in this method Thread.Sleep(1); // assign the decremented value // and display the results Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name,counter); } } }
Output (excerpts):
Started thread ThreadOne Started thread ThreadTwo Thread ThreadOne. Incrementer: 1 Thread ThreadTwo. Incrementer: 2 Thread ThreadOne. Incrementer: 3 Thread ThreadTwo. Incrementer: 4 Thread ThreadOne. Incrementer: 5 Thread ThreadTwo. Incrementer: 6 Thread ThreadOne. Incrementer: 7 Thread ThreadTwo. Incrementer: 8 Thread ThreadOne. Incrementer: 9 Thread ThreadTwo. Incrementer: 10 Thread ThreadOne. Incrementer: 11 Thread ThreadTwo. Incrementer: 12 Thread ThreadOne. Incrementer: 13 Thread ThreadTwo. Incrementer: 14 Thread ThreadOne. Incrementer: 15 Thread ThreadTwo. Incrementer: 16 Thread ThreadOne. Incrementer: 17 Thread ThreadTwo. Incrementer: 18 Thread ThreadOne. Incrementer: 19 Thread ThreadTwo. Incrementer: 20
Using Locks
A lock marks a critical section of the code, provides synchronization to an object.
public void Incrementer( ) { try { while (counter < 1000) { lock (this) { int temp = counter; temp ++; Thread.Sleep(1); counter = temp; } // assign the decremented value // and display the results Console.WriteLine("Thread {0}. Incrementer: {1}",Thread.CurrentThread.Name,counter); } }
Using Monitor
There are situations where the programmer need to monitor the running threads for which we can use the followings.
Monitor.Enter(this);
Race Condition and Deadlocks
There are situations when the Process goes for deadlock situation. Synchronization is little tricky to handle.
Race Conditions
This situation occurs when success of one program is depends on uncontrolled order of execution of certain processes(Two Independent Threads).
We can over come this situation by sing Join() and using Monitor() Wait() etc...
Deadlocks
In the situations when one thread is dependent on the other thread to complete it is some time possible that unknowingly one thread can wait for the other to finish, so the second thread can go ahead and run the 2nd process. In few occasions each thread may go in a loop to wait for the next thread to complete the processing to start. where both the threads are waiting for each other to complete and none of them are actually doing any processing.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other
Visual Studio release. Work more productively and collaboratively-with
greater control over your work at every step. The Beta 2 can give you a
head start on achieving efficiency.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|