Multithreading in C#

Discussion in 'C#' started by coderzone, May 20, 2009.

  1. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    39
    Trophy Points:
    28
    Multithreading has been there in the world of computer programming for years. Although, almost all developers pretend to know what multithreading is, it looks like multithreading requires a little more attention when implementing in the real world. Of course, multithreading is easy to understand when it is just a theory, but the practical business application is found to be difficult especially if the developer is not thorough with the basics of multithreading.

    There have been quite a few suggestions by expert programmers that most programmers have overlooked multithreading. As a result, there are more and more errors created in their code, costing thousands of dollars to the businesses and software companies.
    This brief discussion is just an introduction for novice programmers in .NET.

    What is Multithreading?

    Multithreading can be loosely defined as trying to do more than one thing at a time.
    A thread is the flow of the running program which follows instructions written in the code. Before the introduction of multithreading, there was only one thread running for processes in operating systems.

    Imagine a scenario where you can browse the web through a web browser and while typing a document in Microsoft Word at the same time. In this case, you get two things done using two programs. Apply the same concept for a single process and what you get as the result is what multithreading is.

    There are two scenarios that can be applied for multithreading; the threads that do pure calculations and threads that wait for output for further execution. In the first scenario, threads do not have dependencies. They just perform independent calculations where they do not wait for any 3rd party inputs. In this scenario, there is no real sense of using multithreading as it only consumes the processor power in vain as the processor is required to switch between the threads frequently.

    The second scenario is where multithreading is used effectively. In this case, the threads wait for some external inputs and the processor can switch to another thread while the previous thread awaits input. This is rather a smarter way of executing programs without wasting computer’s processing power.

    Multithreading in .NET

    .NET is designed from scratch to support multithreading. There are two main ways of implementing multithreading in .NET; starting threads with ‘ThreadStart delegates’ (also known as the manual method), or using ‘ThreadPool class’.

    If a thread is supposed to be running for a longtime, it is recommended to use ‘ThreadStart’ and manually initiate the thread. If the thread is to run for a brief period, then the smartest way is to use the ‘ThreadPool class’.

    The Simplest Multithreading Example

    Here is one of the most basic multithreaded programs written in C#.
    Code:
    using System;
    using System.Threading;
    
    public class TestThreading
    {
        static void Main()
        {
            ThreadStart job = new ThreadStart(ThreadJob);
            Thread thread = new Thread(job);
            thread.Start();
            
            for (int i=0; i < 4; i++)
            {
                Console.WriteLine ("First Thread: {0}", i);
                Thread.Sleep(1000);
            }
        }
        
        static void ThreadJob()
        {
            for (int i=0; i < 8; i++)
            {
                Console.WriteLine ("Remaining Threads: {0}", i);
                Thread.Sleep(500);
            }
        }
    }
    
    This program creates the following output on my machine
    First Thread: 0
    Remaining Threads: 0
    Remaining Threads: 1
    First Thread: 1
    Remaining Threads: 2
    Remaining Threads: 3
    First Thread: 2
    Remaining Threads: 4
    Remaining Threads: 5
    First Thread: 3
    Remaining Threads: 6
    Remaining Threads: 7
     
    sbglobal123 likes this.
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  3. LenoxFinlay

    LenoxFinlay Banned

    Joined:
    Apr 15, 2009
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    Write a C++ program with a main() function and two thread functions, ThreadFunc1 and ThreadFunc2. Both ThreadFunc1 and ThreadFunc2 should be declared with the usual Win32 API signature for thread functions. ThreadFunc1 should be able to access an argument of type double and simply print out the double value passed to it along with the thread's ID. ThreadFunc2 should be able to access an argument of type int and simply print out the int value passed to it along with the thread's ID. In your main() function, create two threads: one with ThreadFunc1 as the thread function input along with an initialized argument, and the other with ThreadFunc2 as the thread function input along with an initialized argument. Your main() function should wait for the two threads to finish executing, and then print an exit message before ending the program gracefully.

    I'm lost, any examples of what I'm supposed to do or just input to help explain it better is appreciated.
     
  4. satyedra pal

    satyedra pal New Member

    Joined:
    Mar 26, 2010
    Messages:
    93
    Likes Received:
    1
    Trophy Points:
    0
    Multithreading is a specialized form of multitasking.A program is divided into more then one thread.Thread is a single flow of control.And these all thread runs concurrently is called multithreading.
     
  5. muthuis

    muthuis New Member

    Joined:
    Oct 16, 2010
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.codersource.net
    IMHO, multi threading using ThreadPool is the best option as it avoids overloading the CPU and removes a lot of performance bottlenecks..

    Threadpool gets the threads allocated from the underlying framework and thus avoids lots of complications.
     
  6. kumarmannu

    kumarmannu Banned

    Joined:
    Feb 2, 2011
    Messages:
    51
    Likes Received:
    0
    Trophy Points:
    0
    A thread is nothing more than a process.

    The C# .Net language has a powerful namespace which can be used for programming with Threads as well as Thread Synchronization in C# .Net programming. The name of the namespace is Sytem.Threading. The most important class inside this namespace for manipulating the threads is the C# .Net class Thread. It can run other thread in our application process.
    Sample program on C# Multithreading - C# Tutorial:

    The example it creates an additional C# .Net class Launcher. It has only one method, which output countdown in the console.

    Code:
    //Sample for C# tutorial on Multithreading using lock
    
        public void Coundown()
        {
    
            lock(this)
            {
    
                for(int i=4;i>=0;i--)
                {
    
                    Console.WriteLine("{0} seconds to start",i);
    
                }
    
                Console.WriteLine("GO!!!!!");
    
            }
    
        } 
    
    There is a new keyword lock inside the above chunk of .Net C# tutorial code. This provides a mechanism for synchronizing the thread operation. It means at the same point of time only one thread can access to this method of created object. Unless the lock is released after completion of the code, the next routine or iteration cannot enter the block.
     
    Last edited by a moderator: Feb 18, 2011
  7. nicolerisse

    nicolerisse Banned

    Joined:
    Feb 18, 2011
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    I´m sorry, but in my opinion you nerds need someone to talk with...
     
  8. donor

    donor Banned

    Joined:
    Jan 12, 2012
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    web developer
    Location:
    india
    Code:
    class ThreadTest
    {
      static void Main()
      {
        Thread t = new Thread (WriteY);          // Kick off a new thread
        t.Start();                               // running WriteY()
     
        // Simultaneously, do something on the main thread.
        for (int i = 0; i < 1000; i++) Console.Write ("x");
      }
     
      static void WriteY()
      {
        for (int i = 0; i < 1000; i++) Console.Write ("y");
      }
    }
    
    JOIN and THREAD:- 
    
    static void Main()
    {
      Thread t = new Thread (Go);
      t.Start();
      t.Join();
      Console.WriteLine ("Thread t has ended!");
    }
     
    static void Go()
    {
      for (int i = 0; i < 1000; i++) Console.Write ("y");
    }
     
    Last edited by a moderator: Jan 13, 2012

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice