Best practice: when to post back to UI

I have a question about the best paktik. When is the best time to send a callback to the UI when using the loading helper method like below? Button1 uses the Dispatcher on return, and Button2 allows the helper load class to encapsulate the dispatcher call. I prefer Button2.

private void Button1_Click(object sender, RoutedEventArgs e)
{
    AsyncLoader.LoadAsyncWithoutDispatcher(delegate(string result)
    {
        this.Dispatcher.Invoke((Action)delegate { this.TextBox1.Text = result; });
    });
}

private void Button2_Click(object sender, RoutedEventArgs e)
{
    AsyncLoader.LoadAsyncWithDispatcher(this.Dispatcher, delegate(string result)
    {
        this.TextBox1.Text = result;
    });
}

class AsyncLoader
{
    public static void LoadAsyncWithoutDispatcher(Action<string> completed)
    {
        var worker = new AsyncClass();
        worker.BeginDoWork(delegate(IAsyncResult result)
        {
            string returnValue = worker.EndDoWork(result);
            completed(returnValue);
        }, null);
    }

    public static void LoadAsyncWithDispatcher(Dispatcher dispatcher, Action<string> completed)
    {
        var worker = new AsyncClass();
        worker.BeginDoWork(delegate(IAsyncResult result)
        {
            string returnValue = worker.EndDoWork(result);
            dispatcher.Invoke(completed, returnValue);
        }, null);
    }
}

      

0


source to share


1 answer


If the code is generic and not very WPF infrastructure dense, the first method is definitely more general because it completely ignores the use of the dispatcher object. If your class is tightly integrated into WPF, the second method is best practice, since you must call the method using the dispatcher. In the first method, you don't need to specify a dispatcher at all. This is of course not recommended in WPF.



0


source







All Articles