null reference problems with c#
- by alex
Hi:
In one of my window form, I created an instance of a class to do some works in the background. I wanted to capture the debug messages in that class and displayed in the textbox in the window form. Here is what I did:
class A //window form class
{
public void startBackGroundTask()
{
B backGroundTask = new B(this);
}
public void updateTextBox(string data)
{
if (data != null)
{
if (this.Textbox.InvokeRequired)
{
appendUIDelegate updateDelegate = new appendUIDelegate(updateUI);
try
{
this.Invoke(updateDelegate, data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
updateUI(data);
}
}
}
private void updateUI(string data)
{
if (this.Textbox.InvokeRequired)
{
this.Textbox.Invoke(new appendUIDelegate(this.updateUI), data);
}
else
{
//update the text box
this.Textbox.AppendText(data);
this.Textbox.AppendText(Environment.NewLine);
}
}
private delegate void appendUIDelegate(string data);
}
class B // background task
{
A curUI;
public b( A UI)
{
curUI = UI;
}
private void test()
{
//do some works here then log the debug message to UI.
curUI.updateTextBox("message);
}
}
I keep getting a null reference exception after
this.Invoke(updateDelegate, data);
is called.
I know passing "this" as a parameter is strange. But I want to send the debug message to
my window form.
Please help.
Thanks