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.
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);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With