0
我有一個關於最佳實踐的問題。在使用下面兩種幫助程序加載方法時,什麼時候是最好的時間來調用回調用戶界面? Button1在返回時使用Dispatcher,Button2允許幫助器加載類在分派器上封裝調用。我傾向於Button2。最佳實踐:何時返回UI線程
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);
}
}