Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wait for the result from Dispatcher Invoke?

Tags:

c#

wpf

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.

like image 603
Paul Mrozowski Avatar asked Nov 30 '25 02:11

Paul Mrozowski


1 Answers

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);
        }
    });
}
like image 157
Charles Mager Avatar answered Dec 01 '25 15:12

Charles Mager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!