C#WPF UI在UI线程中更新数据时挂起

标签 c# wpf multithreading

在 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/

相关文章:

WPF 绑定(bind)到对象

java - 从声明类以外的类访问 Java ThreadLocal 对象

c# - 需要从电子邮件创建指向 MVC 页面的链接

c# - MVC 应用程序中的文件下载

c# - 编写 Windows 窗体应用程序时 Application.StartupPath 和 AppDomain.CurrentDomain.BaseDirectory 之间的首选项

c# - C++ C# 包装器相关。如何从 C# 窗口获取 hwnd 并将其传递给 C++?

c# - 在 C# 中安装应用程序之前执行一些操作

c# - 访问 ObservableCollection 中的项目绑定(bind)到 WPF DataGrid

android - 如何通过读/写 BLE Gatt 特性实现最大的线程安全性?

与 CPU 核心数量相关的多线程和并行性