我是C#
Task
和线程的新手。C#更新UI在任务
我有象下面这样的代码: -
public void UpdateSales(object sender, EventArgs args)
{
Task.Run(() =>
{
// Some code Create Collection ...
// Some code with business logic ..
// Below code is to update UI
// is it safe to update UI like below
saleDataGrid.Dispatcher.Invoke((Action) (() =>
{
saleDataGrid.ItemsSource = currentCollection;
saleDataGrid.Items.Refresh();
}));
});
}
我不知道如果这个代码是否正确。我认为无论如何都会发生僵局?
你能指点我如何从任务更新UI?我没有使用async/await
,因为UpdateSales
是来自第三方库的事件处理程序。
通常您只需调用Dispatcher并检查是否需要调用它的特定线程。但是我很确定你的代码不会导致死锁 –