Performing Operation on Richtext box from another thread another class
m having problem in operating on richtextbox from another class
m using backgroundworker class to seperate GUI thread from the computation thread
this is the function i need to call from other class
public void UpdateRTB(String strText, Color colVar)
{
if (InputBox.InvokeRequired)
{
InputBox.Invoke(new UpdateRTBCallback(this.UpdateRTB), new object[] { strText, colVar });
}
else
{
InputBox.Select(InputBox.Text.IndexOf(strText), strText.Length);
InputBox.SelectionColor = colVar;
InputBox.Update();
}
}
the variable objForm1 is the variable declared after initialization of the form as
objForm1 = this;
the function which return the form is
public static Form1 GetThisForm()
{
return objForm1;
}
this is my delegate which is declared globally
public delegate void UpdateRTBCallback(String strText, Color strColor);
this is the code m writing in another class to call it
Form1 form1 = Form1.GetThisForm();
form1.UpdateRTB(item, Color.Yellow);
in the objForm1, when I debug I see the fields of it is showing System.InvalidOperationException.. is this the problem of I'm doin开发者_JAVA百科g something wrong Please help!!!
you cannot directly operate on the gui thread from another thread, you need to check InvokeRequired and invoke if calling a method on the gui thread from another thread. in your gui class implement methods you expect to call from other threads using InvokeRequired to check if you need to invoke the action on the gui thread or continue as normal. there is a lot of info on this subject here. Here's a very short demo:
if (this.InvokeRequired) {
// called from non-gui thread, use invoke to delegate the action to the gui thread
MyCallBack callback = new MyCallBack(myCallBack);
this.Invoke(callback, params);
} else {
// called from gui thread, do your thing as normal
}
OK, I'm guessing there's a second possible scenario. The reference to your form gets set after initialization of the form so I guess that's in your form constructor (and I hope it's after InitializeComponent() according to the WinForms guidelines..). The function that returns the reference is static, which means the reference also has to be static, which means you could be looking at it before the constructor of the form got called and before the reference got set. Here I'll have to add you did not show us where you are accessing the reference from (from a (static) function that ran before the form got constructed?).
Anyway, here are some alternatives I'm hoping will be a useful answer / option to you -> instead of writing your own you may want to have a look at these useful helper properties that seem to already do what you need Form.ActiveForm or Application.OpenForms.
PS: System.InvalidOperation may show up for your form's fields because they too are being evaluated from another (debug) thread than the UI thread.
精彩评论