I have a class that manages the UI, which contains this method:
public void SetField(int field, int value)
I have a delegate declared:
public delegate void SetFieldDelegate(int field, int value);
On a buttonpress event, I call a computationally expensive method of another class, on a background thread. The UI doesn’t freeze, the work is being done. On occasion, I want to update the UI though, I tried to use the delegate for this, to avoid cross-thread operations:
Gui.SetFieldDelegate TestDelegate = new Gui.SetFieldDelegate(gui.SetField);
In the heavy working method, I call:
TestDelegate.Invoke(field, value);
But it’s still an invalid cross-thread opeartion. I’m sure it’s something trivial, but I’m lost. Also, any suggestions are welcome, if there is a much easier way to do this.
You’re calling
Invokeon the delegate, which doesn’t do anything about threads – it’s just invoking it synchronously.You need to call
Invokeon an element of the UI, e.g.or
BeginInvokeinstead:That’s assuming you’re using Windows Forms. If you’re using WPF or Silverlight, you need to use
Dispatcher.InvokeorDispatcher.BeginInvokeinstead, e.g.