0

i many time call method with the help of thread like

static void Main( string[] args )
{
    Thread t = new Thread( MyFunction );
    t.Start();
}

static void MyFunction()
{
    //code goes here
}

and some time i use ThreadPool class also like

System.Threading.ThreadPool.QueueUserWorkItem(delegate {
    MyFunction();
}, null);

but i do not understand what is the difference between calling any method with the help of thread class or ThreadPool class

so i am looking a good discussion about what is the difference between Thread & ThreadPool class.also need to know when we should use Thread class to call a method and when ThreadPool class to call any method ? if possible discuss also with sample code with sample situation.

another very important question is that if i start multiple thread then my application performance will become low or bad ? if yes then tell me why...?

now also tell me what is BackgroundWorker class and how it is different from Thread & ThreadPool class. how far i heard that BackgroundWorker class also create a separate thread to run any method. so please discuss how it is different from Thread & ThreadPool class and when one should go for BackgroundWorker class.

here is small sample code of BackgroundWorker

private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw = new BackgroundWorker();

        // this allows our worker to report progress during work
        bw.WorkerReportsProgress = true;

        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            // do some simple processing for 10 seconds
            for (int i = 1; i <= 10; i++)
            {
                // report the progress in percent
                b.ReportProgress(i * 10);
                Thread.Sleep(1000);
            }

        });

        // what to do when progress changed (update the progress bar for example)
        bw.ProgressChanged += new ProgressChangedEventHandler(
        delegate(object o, ProgressChangedEventArgs args)
        {
            label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
        });

        // what to do when worker completes its task (notify the user)
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            label1.Text = "Finished!";
        });

        bw.RunWorkerAsync();
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Mou
  • 15,673
  • 43
  • 156
  • 275
  • 3
    This is not a good question for [so]. It's a book's worth of information. – John Saunders Mar 11 '14 at 19:16
  • 1
    [Many](http://stackoverflow.com/questions/6913487/c-sharp-downloader-should-i-use-threads-backgroundworker-or-threadpool) [existing](http://stackoverflow.com/questions/4757159/difference-between-backgroundworker-and-thread) [answers](http://stackoverflow.com/questions/17008550/thread-threadpool-or-backgroundworker). – Adam Houldsworth Mar 11 '14 at 19:16
  • creating a thread is an expensive operation. about 200,000 cycles to create and 100,000 cycles when you're done with it. Using pre-created threads (e.g. the ThreadPool) is recommended. Use BackgroundWorker when you need to offload processing from the UI thread and still require progress/cancellation--or use Task. – Peter Ritchie Mar 11 '14 at 19:23
  • Thread is your classic thread, just makes a new job and runs it in a new thread. Thread pool is a way to manage the number of threads that you create. For example, create a thread pool of 10 threads, get one from the pool, execute some job, put it back in the pool for use later. The BackgroundWorker class helps by setting up hooks to the UI thread to update your app. Since you can only change the UI on the main UI thread, the RunWorkerCompletedEventHandler and ProgressChangedEventHandler execute on the UI thread so you don't have to worry about looking it up first. – CaptRespect Mar 11 '14 at 19:25
  • @Mou: You may find [an old blog post of mine](http://blog.stephencleary.com/2010/08/various-implementations-of-asynchronous.html) useful. – Stephen Cleary Mar 11 '14 at 19:29

1 Answers1

22

but i do not understand what is the difference between calling any method with the help of thread class or ThreadPool class

The main difference is whether you manage the thread lifetime yourself (Thread), or you take advantage of the "pool" of threads the framework already creates.

Using ThreadPool.QueueUserWorkItem will (often) use a thread that already exists in the system. This means you don't have the overhead of spinning up a new thread - instead, a set of threads is already there, and your work is just run on one of them. This can be especially beneficial if you're doing many operations which are short lived.

When you use new Thread, you actually spin up a new thread that will live until your delegate completes its execution.

Note that, as of .NET 4 and 4.5, I'd recommend using the Task and Task<T> types instead of making your own threads, or using ThreadPool.QueueUserWorkItem. These (by default) use the thread pool to execute, but provide many other useful abstractions, especially with C# 5 and the await/async keywords.

now also tell me what is BackgroundWorker class and how it is different from Thread & ThreadPool class. h

The BackgroundWorker class is an abstraction over the thread pool. It uses the ThreadPool to queue up "work" (your DoWork event handler), but also provides extra functionality which allows progress and completion events to be posted back to the initial SynchronizationContext (which, in a GUI program, will typically be the user interface thread). This simplifies tasks where you want to update a UI for progress or completion notifications as background "work" is running on a background thread.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 5
    Curious why the downvoting here... :) – Reed Copsey Mar 11 '14 at 19:23
  • i guess all thread classes are by default foreground thread but BackgroundWorker only deals with background thread....why ?? give some insight about fore ground & background thread if possible. – Thomas Mar 12 '14 at 08:37
  • @Thomas The thread pool uses backgroudn threads. In general, that's what people want - the only way to get foreground threads is to make your own. – Reed Copsey Mar 12 '14 at 17:48
  • Thread t = new Thread( MyFunction ); t.Start(); when we create thread with thread class then what is default type of thread is created....is it background or foreground ?? – Mou Mar 12 '14 at 18:25
  • @Mou Foreground - see: http://msdn.microsoft.com/en-us/library/h339syd0(v=vs.110).aspx – Reed Copsey Mar 12 '14 at 18:30