Calling delegate from another thread do not allow me to modify controls on the form

  • Thread starter Thread starter German Koninin
  • Start date Start date
G

German Koninin

Hi there.
Quite self explained subject. I have a form where are few controls (edit
boxes mostly). and I need to make some kind of search on the background. for
that I made a separated class where I have a function that do actual search.
Olso I have a delegate function defined there. No I need when search is
completed callback function will be called on my form's side and text boxes
will be filled. the problem is that if I try to run my code it say:
Cross-thread operation not valid. So the function is running in context of
my worker thread which is wrong. So could you please suggest me model which
I have to use?
Thanks.

German Koninin
 
look at Control.Invoke or Control.BeginInvoke; basically, you need to push
the last steps back onto the UI thread so you can talk to the form.

Marc
 
Sounds good. But I can't pass Text property to the Invoke method. I mean the
code is like this: edtName.Invoke(edtName.Text, "Test");
But it wont compile telling me that I have to provide a method, not a
property.
 
In 2.0, you can use tricks like

edtName.Invoke((MethodInvoker) delegate {
edtName.Text = "Test";
});

Note that if you are updating multiple controls, it would be better to do it
all in one Invoke, to avoid lots of posts... so (where "this" is the Form):

this.Invoke((MethodInvoker) delegate {
edtName.Text = newName;
chkEnabled.Value = isEnabled;
txtDescription.Text = newDescription;
});

etc

Marc
 
You can use .InvokeRequiered property of the control that you are trying to
update, to see if it needs invocation. The best appropach would be to write
a method which would check InvoekeRequierd then do the update there.

Check the code below:

delegate void UpdateTextDelegate(string message);
private void UpdateText(string message)
{
if(textBox.InvokeRequired)
{
textBox.Invoke(new UpdateTextDelegate(UpdateText), new object[] {
message });
}
else
textBox.Text = message;
}


Hope this helps

Fitim Skenderi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top