(免责声明:我是 C# 的新手,只是想弄清楚)
从多个线程与 UI 交互时是否有“最佳实践”?我已经看到一些人建议Invoke
每个数据加载器,但其他人建议数据收集线程应该以某种方式通知 UI 线程,并依靠该线程来适当地更新 UI。我更喜欢后者,所以在绘图线程中有一个共享的对象列表和一个循环来显示和删除此列表中的任何内容会更好吗?或者我喜欢的另一个想法是拥有包含控件(或顶级窗口)的方法,例如NotifyDoneGatheringUserList(List<string> names
and NotifyDoneGatheringUserData(User user)
,因此收集线程不需要知道任何关于共享对象的想法;如果这是可行的,是否有一种System.Window.GetMainWindow()
功能风格,或者每次我生成一个收集器时我是否需要/想要传入对象new Thread(GetUserDataFromUser(user, this))
为了显示:
调用
public MainWindow()
{
new Thread(GetUsers());
public void GetUsers()
{
List<string> users;
<load users here>
mainWindow.Invoke((delegate){userList.Text = users.ToString()});
}
共享对象
public MainWindow()
{
new Thread(GetUsers());
// somehow start a look to handle UI updates here without blocking...have to investigate.
}
private Loop()
{
while (true)
{
lock(sharedList);
if (!sharedList.empty())
{
userList.Text += sharedList.Front().ToString();
sharedList.PopFront();
}
sharedList.Unlock();
Sleep(50);
}
}
// data gathering class
public void GetUsers()
{
List<string> users;
<load users here>
lock(mainWindow.sharedList);
mainWindow.sharedList.Push(users)
unlock(mainWindow.sharedList);
}
暴露的方法
public MainWindow()
{
new Thread(GetUsers());
// somehow start a look to handle UI updates here without blocking...have to investigate.
}
private Loop()
{
while (true)
{
lock(sharedList);
if (!sharedList.empty())
{
userList.Text += sharedList.Front().ToString();
sharedList.PopFront();
}
sharedList.Unlock();
Sleep(50);
}
}
public void NotifyUsersLoaded(List<string> users)
{
lock(this.sharedList);
this.sharedList.Push(users)
unlock(thissharedList);
}
// data gathering class
public void GetUsers()
{
List<string> users;
<load users here>
mainWindow.NotifyUsersLoaded(users)
}