我是 C#
Task
和线程的新手。
我有如下代码:-
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();
}));
});
}
我不确定这段代码是否正确。我认为无论如何都会发生死锁?
你能指出我如何从任务更新用户界面吗?我没有使用 async/await
因为 UpdateSales
是来自第三方库的事件处理程序。
最佳答案
如您所知,Task.Run将在线程池线程上执行。
然后您可以使用 ContinueWith它将在该任务完成时运行 - 如果您选择 one of the overrides允许您指定一个 TaskScheduler 然后您可以使用 TaskScheduler.FromCurrentSynchronizationContext()它将使用您输入方法的同步上下文 - 如果这是一个 UI 线程(例如,您在 UI 事件的事件处理程序中),那么同步上下文将是 UI 线程的同步上下文。
所以你的代码看起来像这样:
Task.Run(() => {
//...code to create collection etc...
}).ContinueWith(() => {
saleDataGrid.ItemsSource = currentCollection;
}).TaskScheduler.FromCurrentSynchronizationContext());
关于C# 在任务中更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829873/