tags:

views:

633

answers:

1

I have a question on best pactices. When is the best time to dispatch a call back to the UI when using a helper loading method like the two below? Button1 uses the Dispatcher when returned and Button2 allows the helper loading class to encapsulate the call on the Dispatcher. I tend to favor the 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);
    }
}
A: 

If the code is generic and not really tight to WPF infrastructure, the first method is definitely more generic as it completely ignores the use of a dispatcher object. If your class is tightly integrated to WPF, the second method is a better practice since you have to call the method using a Dispatcher. In the first method, it's possible to not specify dispatcher at all. This is certainly not a recommended thing in WPF.

Mehrdad Afshari