tags:

views:

40

answers:

3

It is a cross threaded operation in windows application done in c#, How can i change it ?

+1  A: 

You need to use a delegate and invoke...

private delegate void SetLabelSub(string NewText);
private void SetLabel(string NewText)
{
 if (this.InvokeRequired()) {
  SetLabelSub Del = new SetLabelSub(SetLabel);
  this.Invoke(Del, new object[] { NewText });
 } else {
  SomeLabel.Text = NewText;
 }
}

Then you can just call SetLabel("New Text Here") from any thread

Basiclife
How roundabout. Just write `Invoke(new Action(() => SomeLabel.Text = NewText));`. The performance impact of doing the invoke when not strictly necessary is negligible, and in 99% of the cases the programmer already knows that it’s always gonna be called from another thread anyway.
Timwi
A very valid point - But I was going for explicit :)
Basiclife
A: 

If you're dealing with threads you need to use the form.Invoke() method, assuming you're passing the form instance into the other form. roughly Form form1 = new Form() Form form2 = new Form(); form2.CallingForm = form1; < make this property or what ever

inside form2 add some code like

form1.Invoke(someDelagate, value);

I don't do winforms that often but if you google form.Invoke you'll get some good examples of how to do cross thread operations.

cdmdotnet
Well there ya go, the next post show you how to write invoke methods.
cdmdotnet
+2  A: 

You can write a method which you can call from any thread:

private void SetLabel(string newText)
{
    Invoke(new Action(() => SomeLabel.Text = NewText));
}

Then you can just call SetLabel("Update the label, please") from any thread.

However, your question title states “from another Form” rather than “from another thread”, so it is unclear what you actually mean. You don’t need multithreading if you just want to have multiple forms. You should use threads only for tasks, e.g. downloading a file, copying a file, calculating a value, etc., but not for Forms.

Timwi