开发者

Background worker help. VERY basic

开发者 https://www.devze.com 2022-12-10 12:10 出处:网络
namespace BackgroundWorkerExample { public partial class Form1 : Form { public Form1() { InitializeComponent();
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)


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.


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();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消