views:

99

answers:

3

Hi All

I have been reading the articles on MSDN, but my mind is dead (this usually happens when I read MSDN (No offense MSDN, but your articles confuse me at times.)), and I'm trying to do some "background work" in my app, but not sure how. It's just a single method. But the application hangs, and I have to wait up to 1 - 3 minutes for it to become ...unhanged?

Are there any simple examples that are laying 'round online somewhere that I can have a look at/play around with?

Thank you all

+5  A: 

Jon Skeet wrote a nice introduction to multithreading in .NET that you might read. It also covers threading in WinForms. It may go among the lines:

public partial class Form1 : Form
{
    private BackgroundWorker _worker;

    public Form1()
    {
        InitializeComponent();
        _worker = new BackgroundWorker();
        _worker.DoWork += (sender, e) =>
        {
            // do some work here and calculate a result
            e.Result = "This is the result of the calculation";
        };
        _worker.RunWorkerCompleted += (sender, e) =>
        {
            // the background work completed, we may no 
            // present the result to the GUI if no exception
            // was thrown in the DoWork method
            if (e.Error != null)
            {
                label1.Text = (string)e.Result;
            }
        };
        _worker.RunWorkerAsync();
    }
}
Darin Dimitrov
Thank you Darin, I was still reading Jon Skeet's articles that you mentioned. Very interesting and helpful. Thanks for writing up a sample for me :) It's much appreciated! I'm testing it out now. :-)
lucifer
+1  A: 

Darin already told you the theory.

But you should check out the static ThreadPool.QueueUserWorkItem method. It's more convenient.

Venemo
+1  A: 

There is already this decent question with lots of links to articles that are more easily digestable than MSDN.

Jon Skeet's article is the easiest and probably the most comprehensive to get started with, and Joe Duffy's series goes into a lot of depth. Browsing the C# & Multithreading tags in Stackoverflow also gives you some good answers.

You might find avoiding the BackgroundWorker the fastest way to get going, and simply use an Invoke:

void ButtonClick(object sender,EventArgs e)
{
    Thread thread = new Thread(Worker);
    thread.Start();
}

void Worker()
{
    if (InvokeRequired)
    {
        Invoke(new Action(Worker));
        return;
    }

    MyLabel.Text = "Done item x";
}

Some people like using the BackgroundWorker on Stackoverflow, others don't (I'm in camp number 2).

Chris S
Wow this looks surprisingly simple! And the code that I am using to perform the operation... Do I just put that anywhere inside the Worker() method? P.S. Thank you! :)
lucifer
@j-t-s Anywhere after the `InvokeRequired`, which is only there to swap to the UI thread so you can update your controls without getting an exception.
Chris S
I wish I could upvote this twice
lucifer