views:

78

answers:

3

I have been fighting with multi threading for few days.

I dont understand what are different ways of multithreading. I have read little bit about backgroundWorker, little bit about creating an object of thread. Yesterday I saw in delegate example to implement multithreading by calling BeginInvoke.

I dont understand are these different ways of multithreading or are same working on same background class. Please help me in making it clear to me.

+2  A: 

I like this explanations very much. Maybe they help you, too.
And then, there is this article by Jon Skeet, too.

tanascius
It's very good explanation and part of the book. Really well written.
MadBoy
+1  A: 

any thread without a GUI is a background worker. on dot net the common way to use threads is by creating a thread object and give it a thread main method so, this function will be executed on background firt i think you should read the following books to get a deeper Knowledge on the subject

  • .NET Multithreading
  • C# Threading Handbook

in addition on a GUI app, like WPF or win form app, the only thread that can change the gui elements is the main thread (gui thread), so you should use begininvoke using this thread and put there a callback to change the gui, otherwise you get an invalid operation exception.

another way to use thread would be using the thread pool of .net like these

   ThreadPool.QueueUserWorkItem(new WaitCallback(delegateMethod), data);

 private void delegateMethod(object data){
   //some stuff
 }
Sebastian Marcet
A: 

First, let me say that you don't do multithreading unless it is absolutely necessary. Trying to avoid and optimize your code in the most proficient way will do somehow best, as you will avoid multhreading troubles.

Second, the BackgroundWorker class is a good start. You will need to instantiate as many instances as you require threads to be run. For each of them, you will have to code its DoWork() method. This method is called when you launch its operation by calling the BackgroundWorker.RunWorkerAsync() method. The code you want to place in the DoWork() event is the code that shall be asynchronously run in the background while your application's main thread gets busy with something else. The other two events : ProgressChanged() and RunWorkerCompleted() are used to ReportProgress() or to define what to do when the thread has done its job, whatever end it is (Exception, properly ended, etc.) I use BackgroundWorker most of the time, as it is, in my humble point of view, the simplest to be used.

Third, you can use the System.Threading.Thread class. It is a bit more complicated then just defining a DoWork() event and making it occur by calling another method. You will have to get acquainted with delegates. In short, delegates are types of method or function that are used to execute some work in the background. As for these delegates, you may have multiple methods of the same delegate type, as I just said, delegates are method types. You may have multiple references of a delegate. You may see it also as a method signature. Then, when comes the time to use it, you have to reference a method for the wanted delegate. Using the System.Threading.Thread class, you want to take an eye out on the ThreadStart delegate.

delegate void DoWork(object sender);

private void btnProcessWork_Click(object sender, EventArgs e) {
    DoWork doWork = SimpleDoWorkMethod;
    // Then start using the delegate.
    Thread t = new Thread(new ThreadStart(doWork));
    t.Start(); // Launch the thread in background...
    // Do something else while the thread is working !!!
}

private void SimpleDoWorkMethod(object s) {
    // Do some work here...
}

Fourth, think of delegates as an event, as Events are based on delegates. As a matter of fact, you provide a method that will be used to handle an event like the Button_Click(), for instance. To associate your btnProcess.Click event with your btnProcess_Click() method programmatically, you need to write:

btnProcess.Click += new EventHandler(btnProcess_Click);

What you do here is to make the btnProcess.Click event reference your btnProcess_Click() method. Notice the EventHandler delegate with the ThreadStart delegate. They serves quite the same purpose, but for two different reality (GUI event response and multithreading).

Fifth, don't forget to lock a variable before accessing it while another might want to access it at about the same time, then throwing a cross thread or so exception, and this, even for primitive types, but more specifically for collections, as they are not thread-safe.

Hope this helps a bit! =)

Will Marcouiller
IMO "don't do multithreading unless it is absolutely necessary" is a sentiment from the past. It certainly is necessary to make use of multi-core systems, and it is equally necessary to make user-friendly applications in the face of lengthy or potentially blocking operations, which simply shouldn't be done in the UI thread. But luckily new developments like the Task Parallel Library provide better abstractions, and make concurrency in applications much easier.
mghie
Yes, indeed, for instance PLINQ in .NET 4.0 will be awesome to work with. Despite, it is not much a sentiment from the past, but more like a necessity of using multhreading. Most of developed software fulfills a straightforward process, particularly in management software. If we're speaking about a fully transactional messaging system in an industrial process system, that would be different! No, what I mean is simply not to use it when it is not required. Not to overuse threading. ( to be continued... )
Will Marcouiller
Once your application or an iteration of your application is delivered to your customer, and a noticeable lack of performance for a precise task should be corrected, it is only then that you should use multithreading in order to fraction the time required by a process or processes. This is more likely called fine tuning the application. But before fine tuning, one needs to know if his work works. Once it works, then optimize for performance.
Will Marcouiller