2

I think I'm missing something here. I've got a WPF form that has some methods on it I need to call from an external source (usually on a non-UI thread). I retrieve a reference to the form, then attempt to call the method via Dispatcher.Invoke so it's marshalled to the UI thread. The problem is that this code won't work as the Invoke fires an Action, so the result is always an empty string (even though the docs say Invoke is supposed to be synchronous).

 public string GetValueById(string id, string value) { Application.Current.Dispatcher.Invoke(() => { var main = Application.Current.MainWindow as MainWindow; if (main != null) { return main.GetValue(id); } }); return ""; } 

I can't quite wrap my head around how to make this work.

1
  • return Application.Current.Dispatcher.Invoke(() => { etc...}); Commented Sep 11, 2016 at 17:28

1 Answer 1

12

If you look at the documentation for that Dispatcher.Invoke overload, you'll see that if you pass it a Func<TResult> callback then it will return the TResult returned by executing that callback. All you have to do is actually make use the return value:

public string GetValueById(string id, string value) { return Application.Current.Dispatcher.Invoke(() => { var main = Application.Current.MainWindow as MainWindow; if (main != null) { return main.GetValue(id); } }); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.