1

这是我正在尝试制作的同步 url 下载程序的一部分。它将 url 列表保存在名为的数据表中tbl,并绑定到名为 的数据网格视图dgvUrls。每次遇到死 URL 时,都会将其从数据表中删除。

我已经使用下面的代码重现了该错误。将Button3_Click100 行添加到数据表中,使其成为 datagridview 的数据源。通过q()删除第一行一次删除一行。问题是 datagridview 不反映在数据表中所做的更改

    Dim tbl = New DataTable

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    'Add 100 urls, for simplicity i'm adding only integers
    tbl.Columns.Add("Urls")
    For i = 1 To 100
        tbl.Rows.Add(i)
    Next

    'bind to datagridview so that the end user can see the urls being download/removed from the list 
    dgvUrls.DataSource = tbl

    'start multithread download , for simplicited (of this question) we have only one
    Dim t As Thread = New Thread(AddressOf Download)
    t.Start()

   t.Join()
   dgvUrls.Refresh()

End Sub

Private Sub download()
    'for simplicity, the 1st 80 urls were dead!
    For i = 1 To 80
        'we remove the dead urls
        tbl.Rows.RemoveAt(0)
    Next
4

1 回答 1

2

Refresh一般来说,这对来说是件好事DataGridView,主要是当您从另一个线程执行修改时;像这样的东西:

Dim t As Thread = New Thread(AddressOf q)
t.Start()
t.Join() 'Waits for the other thread to complete, such that the next line is reached on the right moment

dgvUrls.Refresh()

Dim ts As ThreadStart = New ThreadStart(AddressOf q)因为没必要我删了。你也不需要Sleepand DoEvents

Private Sub q()
    For i = 1 To 98
        tbl.Rows.RemoveAt(0)
    Next
End Sub

作为概念证明(了解这一切是如何工作的)是可以的;但是在进一步讨论之前,您应该回顾一下逻辑中的各种想法:从其中删除这么多行DataSource可能会引发问题(您会看到它会触发错误);理想情况下,(至少,我更喜欢它)你应该DataGridView直接修改(如果可能的话)以避免信息同步问题;如果您处理多个线程,则必须设置“更合适的结构”(建议t.Join()应被视为使这项工作正常进行的临时修复)。

于 2013-09-21T15:52:44.583 回答