views:

132

answers:

2
namespace BackgroundWorkerExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);
            MessageBox.Show("Now!");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Not working friends!
            backgroundWorker1.RunWorkerAsync(backgroundWorker1_DoWork);
        }
    }
}

How can I call the DoWork method (do I even have to do this? lol)

A: 

Nevermind, I found the answer on my own. Turns out the method doesn't have any parameters for my use case.

namespace BackgroundWorkerExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);
            MessageBox.Show("Now!");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Now it works!
            backgroundWorker1.RunWorkerAsync();
        }
    }
}
Sergio Tapia
But the MessageBox.Show() will probably fail.
Henk Holterman
No, the Show call will work and bring up a model dialog, but note that it won't block you from accessing the Form1 instance. This may sound weird, but the MessageBox is raised from another thread, than the main thread, so this behavior is desirable.
Lex Li
lextm, you're right, I just tested. Learned something again.
Henk Holterman
+1  A: 
backgroundWorker1.RunWorkerAsync();

The argument is optional, used to pass arguments to DoWork:

backgroundWorker1.RunWorkerAsync(10);
backgroundWorker1.RunWorkerAsync(obj);  // Pass multiple arguments using an object

which can be accessed from DoWork using e.Argument cast to the object type.

Gordon Bell