English speaking and learning Interview Questions and Answers Programs C# Concept OOPS Concept JOBS

Sunday, July 2, 2017

MultiThreading in C#




  • Today,we will discuss MultiThreading in C#.Before we discuss multithreading, first let's understand the multitasking.

There are two distinct types of multitasking: 
process-based and thread-based. It is important to understand the difference between the two. 
  •  Process is what the operating system uses to facilitate the execution of a program by providing the resources required. Each process has a unique process Id associated with it. You can view the process within which a program is being executed using windows task manager.Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example, process-based multitasking allows you to run a word processor at the same time you are using a spreadsheet or browsing the Internet. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler. 
  • Thread is a light weight process. A process has at least one thread which is commonly called as main thread which actually executes the application code. A single process can have multiple threads.In a thread-based multitasking environment, all processes have at least one thread, but they can have more. This means that a single program can perform two or more tasks at once. For instance, a text editor can be formatting text at the same time that it is printing, as long as these two actions are being performed by two separate threads.


 The differences between process-based and thread-based multitasking can be summarized like this: Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.

One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. So far we wrote the programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.




  • Single threaded Applications Single threaded applications are those in which a thread cannot execute until the earlier thread has completed its execution.  The MS-DOS operating system is an example of a single threaded operating system.  These environments do not have any support for Multithreading and they monopolize the processor and have low system throughput.  Throughput is a measure of the amount of the job done in unit time.

  • Multithreading Applications Multithreading is the ability of the operating system to have at the same point of time multiple threads in memory which switch between the tasks so as to provide a pseudo parallelism, as if all the tasks are running simultaneously.  This illusion of concurrency is ensured by the Operating System by providing a specific time slice to each and every thread and then switching between the threads once their slice is over.  This switching is very fast.  The switching between the threads involves a context switch which in turn involves saving the current thread’s state, flushing the CPU and handling control of the CPU to the next thread in the queue.  Remember that at any point of time the CPU can execute only one thread.  It is to be noted here that Multiprocessing involves multiple processor with each executing one thread at any particular point of time.
Advantages and Disadvantages of Multithreading

  • To maintain a responsive user interface
  • Faster execution
  • To make efficient use of processor time while waiting for I/O operations to complete.
  • To split large, CPU-bound tasks to be processed simultaneously on a machine that has multiple CPUs/cores. 
  • Support for Concurrency
Disadvantages of multithreading:

  • On a single-core/processor machine threading can affect performance negatively as there is overhead involved with context-switching.
  • Have to write more lines of code to accomplish the same task.
  • Multithreaded applications are difficult to write, understand, debug and maintain

The following states in the life cycle of a thread are:

  • Unstarted State: When the instance of the thread is created but the Start method is not called.

  • Ready State: When the thread is ready to run and waits for CPU cycle.
Not Runnable State: When thread is in the condition, given below:
  • Sleep method has been called.
  • Wait method has been called.
  • Blocked by I/O operations.
The Dead State: When the thread is in the condition, given below:
  • Completes execution.
  • Aborted.
Below are some most used properties,methods and constructors of threading class.

Constructors

Thread(ThreadStart)  Initializes a new instance of the Thread class.
Thread(ParameterizedThreadStart)   Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.

Properties

Name  Gets or sets the name of the thread.
ThreadState Gets a value containing the states of the current thread.
Priority Gets or sets a value indicating the scheduling priority of a thread.
ManagedThreadId Gets a unique identifier for the current managed thread.
IsAlive Gets a value indicating the execution status of the current thread.
CurrentThread Gets the currently running thread.

Methods

Start() Causes the operating system to change the state of the current instance to ThreadState.Running.
Start(Object)  Causes the operating system to change the state of the current instance to ThreadState.Running, and optionally supplies an object containing data to be used by the method the thread executes.
Sleep(Int32) Suspends the current thread for the specified number of milliseconds.
Join() Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM andcSendMessage pumping.
Finalize() Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object. (Overrides CriticalFinalizerObject.Finalize().)
Abort() Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
ToString() Returns a string that represents the current object.(Inherited fromObject.)

Now, i will explain how to start, abort,suspend and resume the thread by example.

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




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 IsAliveproperty 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

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();

15 comments :

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. Get a lot of fun playing with us in the online casino. roulettes free with us We all love to play in the Internet online casino, let's play with us and earn.

    ReplyDelete
  3. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ReplyDelete
  4. Cool stuff you have and you keep overhaul every one of us

    data science course

    ReplyDelete
  5. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  6. It is perfect time to make some plans for the future and it is time to be happy. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it!

    Data Science Course

    ReplyDelete
  7. I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one

    Data Science Training

    ReplyDelete
  8. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.

    data science interview questions

    ReplyDelete
  9. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ReplyDelete
  10. Attend The Data Science Courses From ExcelR. Practical Data Science Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses. data science courses

    ReplyDelete
  11. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    360DigiTMG Data Science Course In Pune
    360DigiTMG Data Science Training In Pune

    Thank you..

    ReplyDelete
  12. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete