Reputation: 64
Let's say i have created a class name myClass and this class has a property named myValue with any type, doesn't matter, like:
class myClass
{
public delegate void OverTheLimitDlg(int arg);
public event OverTheLimitDlg OverTheLimit;
public myClass()
{
myValue = 0;
}
private int myvalue = 0;
public int myValue
{
get { return myvalue;}
set
{
myValue = value;
if(value > 5)
OvertheLimit(value);
}
}
}
I have a winforms label named myLabel on form and i create an object typed myClass at Form Load event, subscribe its OverTheLimit event and start backgroundworker:
myClass myObj;
private void Form_Load(object sender, EventArgs e)
{
myObj = new myClass();
myObj.OverTheLimit += SubsMethod;
backgroundworker.RunWorkerAsync();
}
private void backgroundworker_DoWork(...)
{
myObj.myValue = 10;
//Some expressions.
}
private void SubsMethod(int someInt)
{
myLabel.Text = "Oh it's over the limit!";
}
Summary: i create a class that an object instantiated from it can fire an event. I make the object fire the event in a thread and it runs a method that affects a GUI object, an object created and runs at another thread. I didn't try it ever. What is going to happen in a situation like this? Does it cause error? Thanks.
Upvotes: 0
Views: 72
Reputation: 1766
What is going to happen in a situation like this?
myLabel.Text = "Oh it's over the limit!";
This line will throw an InvalidOperationException
when it tries to edit the myLabel
from the BackgroundWorker thread. WinForms controls must be changed from the thread that they are created on, this is why Control.InvokeRequired
exists.
You can use the following modified version of SubsMethod()
which will check if the event handler is running on another thread and then invoke the label change on the GUI thread if necessary.
private void SubsMethod(int someInt)
{
if (myLabel.InvokeRequired) {
myLabel.Invoke(new MethodInvoker(()=>SubsMethod(someInt)));
return;
}
myLabel.Text = "Oh it's over the limit!";
}
Upvotes: 1