在 UI 线程中更新数据时 UI 卡住 3-10 秒 我想在不卡住的情况下更新 UI 线程中的数据。
代码:
Task t = Task.Factory.StartNew(() =>
{
// Get data from Server
GetData(true);
});
在 Getdata()
内部
//Converst JSON to DataSet Object:- "tempDataSet"
Task task = Task.Factory.StartNew(() =>
{
RetriveData(tempDataSet, firstTime);
}, CancellationToken.None, TaskCreationOptions.None, MainFrame.Current);
在 RetriveData
内部
DataTable response = tempDataSet.Tables["response"];
DataTable conversations = tempDataSet.Tables["convo"];
foreach (DataRow row in conversations.Rows) // UI Hangs in the method
{
UC_InboxControl control = new UC_InboxControl(row, uC_Inbox);
if (uC_Inbox.mnuUnreadChat.IsChecked == false)
{
inboxControlCollection.Add(control);
}
else
{
inboxUnreadOnlyControlCollection.Add(control);
}
}
在不挂起或卡住的情况下在 UI 线程中更新 UI 的最佳方法是什么?
最佳答案
GetData
方法不应访问任何 UI 元素。它应该在后台线程上执行并返回要在 View 中显示的对象列表。然后,您可以使用 ContinueWith
方法在 UI 线程上使用这些对象填充 ObservableCollection
,例如:
Task t = Task.Factory.StartNew(() =>
{
return GetData(true); // <-- GetData should return a collection of objects
}).ContinueWith(task =>
{
//that you add to your ObservableCollection here:
foreach (var item in task.Result)
yourObservableCollection.Add(item);
},
System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
关于C#WPF UI在UI线程中更新数据时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43584821/