2

这是一个代码示例,您需要在表单上ListBox调用list_of_items,以重现我遇到的问题:

Imports System.Threading.Tasks

Public Class Form1
  Dim _dt As DataTable

  Private Sub Form1_Load() Handles MyBase.Load
    _dt = New DataTable
    With _dt.Columns
      .Add("key")
      .Add("value")
    End With
    With list_of_items
      .ValueMember = "key"
      .DisplayMember = "value"
      .DataSource = _dt
    End With
    Dim addItemsTask As New Task(AddressOf AddThreeItems)
    addItemsTask.Start() 'does not add anything when done
    'AddThreeItems() #doing this instead works!
  End Sub

  Private Sub AddThreeItems()
    Threading.Thread.Sleep(2000)
    With _dt.Rows
      .Add({"1", "One"})
      .Add({"2", "Two"})
      .Add({"3", "Three"})
    End With
    Me.Invoke(Sub() Me.Text = "Separate thread is done")
  End Sub
End Class

问题是行确实是物理添加的,所以DataTable.Rows.Count增加了,但视觉上没有任何反应。我试过打电话Refresh,重置和DataSource返回Nothing- 它没有帮助。如果我将其切换为单线程处理,则可以使用图示的方法很好地添加行。可能是什么问题?

4

2 回答 2

1

重新分配数据源

Me.Invoke(
    Sub()
        list_of_items.DataSource = Nothing 
        list_of_items.DataSource = _dt 
        Me.Text = "Separate thread is done"
    End Sub
) 
于 2012-10-24T18:06:33.157 回答
1

我在玩Me.Invoke,发现如果我使用 同步添加一个虚拟记录Invoke,我之前添加的所有记录实际上都会被添加。然后我只需要从DataTable. 如果您有更好的解决方案或更优雅的解决方法,或者您可以解释为什么它会这样工作,请随时将其发布为答案。下面是代码现在的样子:

Private Sub AddThreeItems()
  Threading.Thread.Sleep(2000)
  With _dt.Rows
    .Add({"1", "One"})
    .Add({"2", "Two"})
    .Add({"3", "Three"})
  End With
  Me.Invoke(Sub()
              _dt.Rows.Add()
              _dt.Rows.RemoveAt(_dt.Rows.Count - 1)
              Me.Text = "Separate thread is done"
            End Sub)
End Sub
于 2012-10-24T18:25:44.293 回答