Reputation: 3766
when i compile this code i get his error, object reference set to null, and the error location is in Dowork, argumenttest.valueone = 8;
public partial class Form1 : Form
{
BackgroundWorker bgw1 = new BackgroundWorker();
public Form1()
{
InitializeComponent();
// bgw1.RunWorkerAsync(test1);
test test1 = new test
{
valueone = 5,
valuetwo = 10
};
bgw1.RunWorkerAsync(test1);
}
class test
{
public int valueone { get; set; }
public int valuetwo { get; set; }
}
private void bgw1_DoWork(Object sender, DoWorkEventArgs e)
{
test argumenttest = e.Argument as test;
Thread.Sleep(10);
argumenttest.valueone = 8;
argumenttest.valuetwo = 10;
e.Result = argumenttest;
}
private void bgw1_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
{
test test12 = e.Result as test;
button1.Text = test12.valueone.ToString();// +test.valuetwo.ToString();
//this.Text = test.valueone.ToString() + " "+ test.valuetwo.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
bgw1.DoWork += bgw1_DoWork;
bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;
//bgw1.RunWorkerAsync(test);
}
}
Upvotes: 2
Views: 557
Reputation: 4711
You should subscribe to DoWork and RunCompleted in Form load or before you make a call to RunWorkerAsync.
bgw1.DoWork += bgw1_DoWork;
bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;
move the above lines to Form_Load from Button Click event handler.
And move bgw1.RunWorkerAsync(test1);
to button click handler from Form Load method.
Upvotes: 1
Reputation: 20764
One problem that I see is that you don't set the event handler before you run the worker, so these 2 lines
bgw1.DoWork += bgw1_DoWork;
bgw1.RunWorkerCompleted += bgw1_RunWorkerCompleted;
have to be called before
bgw1.RunWorkerAsync(test1);
Upvotes: 1
Reputation: 60724
There are two possible ways argumenttest
ends up as null
:
argumenttest
was sent as null
into the RunWorkerAsync
.
e.Argument as test;
e.Argument
is something not compliant with test
, and the as
operator makes it null
.
It hard to see which one, since your code example above is quite messed up.
EDIT
Can you confirm that your code is exactly as decyclone edited it? In that case, it looks fine, and should have worked as far as I can see.
Set a breakpoint on the first line of the DoWork method, and when debugging you should be easily able to see if 1. or 2. is the problem by hovering over e.Argument
.
Upvotes: 4