Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Multithreading in C# (http://www.go4expert.com/articles/multithreading-c-sharp-t17618/)

coderzone 20May2009 10:06

Multithreading in C#
 
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: CSharp

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

shabbir 3Jun2009 09:37

Re: Multithreading in C#
 
Nomination this Article for Article of the month - May 2009

LenoxFinlay 11Jun2009 13:02

Re: Multithreading in C#
 
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.

satyedra pal 28May2010 14:24

Re: Multithreading in C#
 
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.

muthuis 17Oct2010 11:02

Re: Multithreading in C#
 
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.

kumarmannu 2Feb2011 16:38

Re: Multithreading in C#
 
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.

nicolerisse 18Feb2011 19:59

Re: Multithreading in C#
 
I´m sorry, but in my opinion you nerds need someone to talk with...

donor 13Jan2012 11:41

Re: Multithreading in C#
 
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");
}



All times are GMT +5.5. The time now is 04:03.