I'm trying to learn delegate and not sure what I do wrong. So I have three classes, Form1, Class1, and Class2. Form1 calls Class1 method to set a string for Class1 member and then Form1 starts workerbackground thread to start Class2. But when Class2 calls Form1 delegate method which will call Class1 method to get string data, but it returns back to Class2 as null.
So this is where it returns null,>> string str = form1Obj.gDelegateClass1GetData(();
This is Form1:
public delegate string DelegateClass1GetData();
public delegate void DelegateClass1SetData(string data);
public partial class Form1 : Form
{
public DelegateClass1GetData gDelegateClass1GetData;
public DelegateClass1SetData gDelegateClass1SetData;
public Class1 class1Obj;
public BackgroundWorker bw_Class2;
public Class2 class2Obj;
public Form1()
{
InitializeComponent();
class1Obj = new Class1();
class2Obj = new Class2(this);
gDelegateClass1GetData = new DelegateClass1GetData(this.Class1GetData);
gDelegateClass1SetData = new DelegateClass1SetData(this.Class1SetData);
}
private void button1_Click(object sender, EventArgs e)
{
class1Obj.setClass1Data("Hello");
bw_Class2 = new BackgroundWorker();
bw_Class2.WorkerSupportsCancellation = true;
bw_Class2.DoWork += new DoWorkEventHandler(ThreadClass2_DoWork);
bw_Class2.RunWorkerAsync();
}
public string Class1GetData()
{
if (InvokeRequired)
Invoke(new DelegateClass1GetData(Class1GetData));
else
{
return class1Obj.GetClass1Data();
}
return null;
}
public void Class1SetData(string data)
{
if (InvokeRequired)
Invoke(new DelegateClass1SetData(Class1SetData), data);
else
{
class1Obj.setClass1Data(data);
}
}
public void ThreadClass2_DoWork(object sender, DoWorkEventArgs e)
{
string str1 = class1Obj.GetClass1Data();
class2Obj.AddString();
}
}
This is Class1:
public class Class1
{
public string gClass1Data;
public Class1()
{
gClass1Data = null;
}
public void setClass1Data(string data)
{
gClass1Data = data;
}
public string GetClass1Data()
{
return gClass1Data;
}
}
This Class2:
public class Class2
{
public Form1 form1Obj;
public Class2(Form1 obj)
{
form1Obj = obj;
}
public void AddString()
{
string str = form1Obj.gDelegateClass1GetData();
str = str + " Delegate";
form1Obj.gDelegateClass1SetData(str);
string str2 = form1Obj.gDelegateClass1GetData();
}
}
The problem is in
Form1.Class1GetData
method. When you callform1Obj.gDelegateClass1GetData()
inClass2.AddString()
, you actually callForm1.Class1GetData
.InvokeRequired
returnstrue
, and you have to callForm1.Class1GetData
again. This time,InvokeRequired
returnfalse
, and you callclass1Obj.GetClass1Data()
, and returns "Hello". It actually returns to the first call toForm1.Class1GetData
, but you returnnull
finally. So, you getnull
tostring str = form1Obj.gDelegateClass1GetData(();
. Try to fix it as