0

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.

Innkeeper
  • 643
  • 1
  • 10
  • 22

2 Answers2

2

You're calling Invoke on the delegate, which doesn't do anything about threads - it's just invoking it synchronously.

You need to call Invoke on an element of the UI, e.g.

form.Invoke(TestDelegate, value);

or BeginInvoke instead:

form.BeginInvoke(TestDelegate, value);

That's assuming you're using Windows Forms. If you're using WPF or Silverlight, you need to use Dispatcher.Invoke or Dispatcher.BeginInvoke instead, e.g.

form.Dispatcher.BeginInvoke(TestDelegate, value);
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1

You need to use either Dispatcher.BeginInvoke(DispatcherPriority.Input, () => { /* do some UI work - updating etc*/ }); for WPF or this.BeginInvoke (new MethodInvoker(() => /* do some UI work - updating etc*/)); for Winforms.

Echilon
  • 9,829
  • 30
  • 130
  • 210