BackgroundWorker,委托InvokeRequired?

时间:2015-12-16 15:12:47

标签: vb.net listview delegates

我一直在使用backgroundWorker和Delegate将listview项添加到listview。我的代码将图像下载到图像列表,然后尝试将图像添加到列表视图。添加了第一个图像,但图像列表中的任何其他图像都无法添加到列表视图中而没有出现跨线程错误。我无法理解为什么第一张图片有效,但没有其他图片有效。通过在这个网站上查看这个主题,我意识到我必须使用InvokeRequired。难道我做错了什么?这是我的代码......

        Dim strPhotoLink As String = strPostContent.Substring(intPhotoLinkStartIndex + 35, ((intPhotoLinkEndIndex - intPhotoLinkStartIndex) - 29))
        lstPhotoLinks.Add(strPhotoLink)
        Try
            ImageListPhotos.Images.Add(Bitmap.FromStream(System.Net.HttpWebRequest.Create(strPhotoLink).GetResponse.GetResponseStream))

            Dim lvi As New ListViewItem("", ImageListPhotos.Images.Count - 1)
            Dim delAddListViewPhotoItem As DelegateAddListViewPhotoItem = New DelegateAddListViewPhotoItem(AddressOf AddListViewPhotoItem)
            delAddListViewPhotoItem.Invoke(lvi)
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try

Private Delegate Sub DelegateAddListViewPhotoItem(item As ListViewItem)
Private Sub AddListViewPhotoItem(item As ListViewItem)
    If ListViewPhotos.InvokeRequired = True Then
        Dim del As New DelegateAddListViewPhotoItem(AddressOf AddListViewPhotoItem)
        ListViewPhotos.Invoke(del, item)
    Else
        ListViewPhotos.Items.Add(item)
    End If
End Sub

0 个答案:

没有答案