线程安全地将子项添加到ListView控件

时间:2011-09-24 19:36:23

标签: .net multithreading listview add

我正在尝试将旧的Windows窗体应用程序转换为WPF应用程序。

以下代码不再在C#.NET 4.0下编译:

// Thread safe adding of subitem to ListView control
private delegate void AddSubItemCallback(
  ListView control,
  int item,
  string subitemText
);

private void AddSubItem(
  ListView control,
  int item,
  string subitemText
) {
  if (control.InvokeRequired) {
    var d = new AddSubItemCallback(AddSubItem);
    control.Invoke(d, new object[] { control, item, subitemText });
  } else {
    control.Items[item].SubItems.Add(subitemText);
  }
}

请帮助转换此代码。

1 个答案:

答案 0 :(得分:0)

希望following blog post能帮到你。在WPF中,您使用Dispatcher.CheckAccess / Dispatcher.Invoke

if (control.Dispatcher.CheckAccess())
{
    // You are on the GUI thread => you can access and modify GUI controls directly
    control.Items[item].SubItems.Add(subitemText);
}
else
{
    // You are not on the GUI thread => dispatch
    AddSubItemCallback d = ...
    control.Dispatcher.Invoke(
        DispatcherPriority.Normal,
        new AddSubItemCallback(AddSubItem)
    );
}