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);
}
}