VisualBuilder
  Home > Csharp > Tutorials > Multi-Threading - C# Tutorial
Tell a friend
Link to us
Total Members
      Members: 84606
     
Sitemap Forum Chat
Home
C# Tutorial Home
1 . Introduction to C sharp
2 . Control Statement: Selection Statement in C sharp
3 . Control Statements – Loops Statement
4 . Methods
5 . Namespaces
6 . Introduction to Classes:
7 . Inheritance:
8 . Polymorphism
9 . Properties
10 . Indexers
11 . Structs
12 . Interfaces
13 . Delegates:
14 . Exception Handling:
15 . Attributes
16 . Enums
17 . Encapsulation
18 . Parameter Passing in C sharp
19 . Method Overloading
20 . Database Interaction Using C sharp
21 . Operator Overloading in C sharp -1
22 . Operator Overloading in C sharp -2
23 . Operator Overloading in C sharp -2
24 . Sockets
25 . DNS [Domain Name System]
26 . Working with Files
27 . Generating Help File in C sharp
28 . Code Access Security
29 . Multi-Threading
30 . Globalization and Localization -1
31 . Working with Registry in C sharp
32 . Globalization and Localization -2
33 . Windows Service
34 . Web Service
35 . Consuming Web Services
36 . Creating Proxy Object of Web Service
37 . Creating an XML document
38 . Reading XML document in C sharp
39 . Using XMLWriter class to Write XML document in C sharp
40 . Assembly Information : Getting Permission set of the assembly
41 . Creating your own Permission Set
42 . Using C sharp Socket
 
Csharp Group Home
Csharp Discussion (7)
Csharp Members (2250)
Csharp Resources
Csharp Source Code (35)
Csharp Articles (0)
Csharp Blogs
Csharp Jobs
Csharp Components (5)
Csharp Books
Csharp Websites (25)
Csharp News (17)
Csharp Q & A (4)
- Csharp Ask Question
- Csharp Questions
- Csharp Unanswered Questions
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.NET Development Tips
ASP.Net Security,Internationalisation And Deployment
ASP.NET Server Controls Tips
ASP.NET Tutorial
C Sharp Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (432 )
Source Code (3217 )
Articles (11 )
Components (1589 )
News (880 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise


Csharp Tutorial
 Multi-Threading
  << Prev: Code Access Security Next: Globalization and Localization -1 >>

A thread is a sequence of execution in a program. All our C# programs up to this point have one entry point—the Main () method. Execution starts with the first statement in the Main () method and continues until that method returns. A thread is the basic unit to which the operating system allocates processor time.


 


Processes are made up of one or more threads. A thread is defined as a single flow of operation within a program. When a program executes on the CPU, it traverses the program statements in a single thread until the thread is complete. A multithreaded application distributes functions among multiple program flows, allowing two or more paths of execution to occur. Each path of execution is a separate thread.


 


Multi-tasking: It's a feature of modern operating systems with which we can run multiple programs at same time example word, excel etc


 


Multi-Threading: Multi-threading forms subset of multi-tasking instead of having to switch between programs this feature switches between different parts of the same program. Example we are writing a word document and at the same time word is doing a spell check in background.


Multithreaded programs create their own threads that can be executed separately from the main thread of the program. All threads created by the primary thread share the same memory address space as the primary thread. Often the secondary threads are used to perform computationally intensive functions, allowing the main thread to continue responding to Windows events. Without the secondary threads, the user could not select anything from the menu or click any buttons while an application computed a mathematical function


 


 


System.Threading: This namespace has all the classes that are related to implement threading. Any .Net application who wants to implements threading has to import this namespace.


Note: In .Net program, there are always at least two threads running, i.e. one is the main program and other is the garbage collector.


 


States:


Threads have several operational states, which are enumerated using the .NET Thread State enumeration, found in the System.Threading namespace.



  • Initialized: The thread has been initialized but not started.

  • Ready: The thread is waiting for a processor.

  • Running: The thread is currently using the processor.

  • Standby: The thread is about to use the processor.

  • Terminated: The thread is finished and is ready to exit.

  • Transition: The thread is waiting for a resource other than the processor.

  • Unknown: The system is unable to determine the thread state.

  • Wait: The thread is not ready to use the processor


 


The Thread Class


 


Use the Thread class to create a new Thread object, which produces a new thread within the current process. The format of the Thread constructor is as follows, where start is a ThreadStart delegate:


Thread (ThreadStart start)

The ThreadStart delegate points to the method that will be performed within the new thread.


 


E.g. Thread newthread= new Thread (new ThreadStart (anyMethod));


Void anyMethod () {}


After the Thread object is created, it can be controlled using various Thread class methods, which are as under:


 



  • Abort (): Terminate the thread.

  • Equals (): Determines whether two thread objects are same.

  • GetHashCode (): Get a unique representation for the thread.

  • GetType (): Get the type of the current thread.

  • Interrupt (): Interrupts a thread that is in a wait state.

  • Join (): Blocks the calling thread until the thread terminates.

  • Resume (): Resumes a thread that has been suspended.

  • Start (): Change the state of the thread to running.

  • Suspend (): Suspend the execution of the thread.

  • ToString (): gets a string representation of the Thread object.


 


Thread priority: The thread priority determines the order in which thread has to execute. The thread priority can be changed by using Threadname.Priority = ThreadPriority.Highest.


Different levels of priority provided by .Net:



  • ThreadPriority.Highest

  • ThreadPriority.AboveNormal

  • ThreadPriority.Normal

  • ThreadPriority.BelowNormal

  • ThreadPriority.Lowest


 


Thread.Sleep (): Thread execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep.


 


 


 


Example: Demonstrate Threading


 


using System;


using System.Collections.Generic;


using System.Text;


using System.Runtime.Remoting;


using System.Threading;


 


namespace ConsoleApplication1


{


  class Program1


   {


    static void Main ( string [] args)


       {


        Program1 ts = new Program1 ();


       }


    public Program1()


        {


            int i;


            Thread firstThread = new Thread ( new ThreadStart (FirstMethod));


            Thread secondThread = new Thread ( new ThreadStart (SecondMethod));


            firstThread.Start();


            secondThread.Start();


      for (i = 0; i < 10; i++)


            {


        Console.WriteLine( "Main: {0}" , i);


                Thread .Sleep(1000);


            }


        }


    void FirstMethod()


        {


            int i;


      for (i = 0; i < 10; i++)


            {


        Console.WriteLine( " First thread: {0}" , i);


                Thread .Sleep(2000);


            }


        }


    void SecondMethod()


        {


            int i;


      for (i = 0; i < 10; i++)


            {


        Console.WriteLine( " Second thread2: {0}" , i);


                Thread .Sleep(3000);


            }


        }


    }


}


 


Output:


Main : 0 First thread: 0 Second thread2: 0 Main : 1 First thread: 1 Main : 2 Second thread2: 1 Main : 3 First thread: 2 Main : 4 Main : 5 Second thread2: 2 First thread: 3 Main : 6 Main : 7 First thread: 4 Main : 8 Second thread2: 3 Main : 9 First thread: 5 Second thread2: 4 First thread: 6 First thread: 7 Second thread2: 5 First thread: 8 Second thread2: 6 First thread: 9 Second thread2: 7 Second thread2: 8 Second thread2: 9

 


  << Prev: Code Access Security Next: Globalization and Localization -1 >>
Csharp Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
LINKS
MSN
Video Surveillance
Skype vs. sipcall
Gift to Pakistan
 
ADVERTISEMENT
 
PARTNER LIST

More
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising