ARTICLE

Multithreading in C#

Posted by Rohatash Kumar Articles | Multithreading in C# July 26, 2011
In this article we will learn how to create threads in C#, start and stop them and define their priorities.
Reader Level:

Multithreading
Multithreading is used to perform multiple tasks at the same time. Tasks with the potential of holding up other tasks can execute on separate threads, a process known as multithreading. Or, it's basically trying to do more than one thing at a time within a process.

Namespace


In .NET, threading functionality is defined in the System.Threading namespace. So you have to define System.Threading namespace before using any thread classes.

using System.Threading;

Starting a Thread


A C# client program starts in a single thread created automatically by the CLR and operating system that is called the main thread, and is made multithreaded by creating additional threads. Here's a simple example and its output.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace multi

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            th.Start();

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

            {

                Console.WriteLine("Hello");

            }

        }

        private static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.Write("world");

            }

        }

 

    }

}

OUTPUT


 starting thread

In the above example, the main thread creates a new thread on which it runs a method that repeatedly prints the string "world". Simultaneously, the main thread repeatedly prints the string "Hello".

Abort a Thread


The Thread class's Abort method is called to abort a thread. Make sure you check the IsAlive property before Abort.

if (Thread.IsAlive)

   {

    Thread.Abort();

      }

 

Here's a simple example and its output.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace multi

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            if (th.IsAlive)

            {

                th.Start();

                th.Abort();

            }

 

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

            {

                Console.WriteLine("Hello");

            }

        }

        private static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.WriteLine("world");

            }

 

        }

    }

 

}

 

OUTPUT

 

Stop thread

In the above example, The main thread creates a new thread which is stopped by the abort method. The main thread repeatedly prints the string "Hello".
Pausing a Thread
The Thread.Sleep method can be used to pause a thread for a fixed period of time.
Thread.Sleep()  

Here's a simple example and its output.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace multi

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            th.Start();

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

            {

                Console.WriteLine("Hello");

                Thread.Sleep(1000);

            }

        }

 

        private static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.WriteLine("world");

                Thread.Sleep(500);

            }

 

        }

 

    }

 

}

 

OUTPUT


Pause a thead

In the above example, the main thread creates a new thread which is paused by the Sleep method for 500 milliseconds. The main thread is also paused by a Sleep method for 1000 milliseconds.

Thread Priority


The Thread class's ThreadPriority property is used to set the thread's priority. The thread priority can have Normal, AboveNormal, BelowNormal, Highest, and Lowest values.
thread.Priority = ThreadPriority.Lowest

Here's a simple example without priority and its output.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace multi

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            th.Start();

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

            {

                Console.WriteLine("Hello");

            }

        }

 

        private static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.WriteLine("world");

            }

        }

    }

}

 

OUTPUT

 

Without priority thread

Using With Lowest Priority

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace multi

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            th.Priority = ThreadPriority.Lowest;

            th.Start();

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

            {

                Console.WriteLine("Hello");

            }

        }

 

        private static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.WriteLine("world");

            }

        }

    }

}

 

OUTPUT


With priority thread

 

In the above example defines the priority, the without priority example executes the method writeY() but in the second example we defined the lowest priority it will execute main method first.

 

Suspend a Thread


The Suspend method of the Thread class suspends a thread. The thread is suspended until the Resume method is called.

if (thread.ThreadState == ThreadState.Running) {

       thread.Suspend();

}

 

 

Resume a suspended Thread
The Resume method is called to resume a suspended thread. If the thread is not suspended, the Resume method will have no effect.

if (thread.ThreadState == ThreadState.Suspended) {

       thread.Resume();

}

Conclusion:


Multithreading is very useful to perform multiple tasks at the same time. If there is any mistake in this article then please notify me. I expect your valuable comments and feedback about this article.

Login to add your contents and source code to this article
post comment
     

Good article for beginners, Thanks

Posted by Micalgray Jul 27, 2011

For the benefit of beginners, Events are very useful for threads. An event such as the AutoResetEvent Class can usually be more effective than the Thread.Sleep method when a thread needs to wait for something. An event is also very useful for stopping a thread in a more controlled manner than the Thread class's Abort method.

Posted by Sam Hobbs Jul 26, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts