Backgroundworker - 完成后无法使用生成的位图
Backgroundworker - Cannot use generated bitmap after completion
您好,在处理完成后,我无法将在 BackgroundWorker 的 DoWork 处理程序中生成的图像数据分配给图像对象。我收到一条错误消息,指出 "the calling thread cannot access this object because a different thread owns it"。错误行是
PreviewImage.Source = Bmp
我的DoWork处理程序代码如下:
Private Sub QueryForAssociatedData(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BW_DrawSideBarImage.DoWork
Using Context As New MyContext
Try
Dim bmp2 As New BitmapImage
bmp2.BeginInit()
bmp2.StreamSource = New MemoryStream(SidebarImageBytes)
bmp2.EndInit()
'Dispatcher.Invoke(Sub() PreviewImage.Source = bmp2)
e.Result = bmp2
Catch ex As Exception
End Try
End Using
End Sub
我希望能够以通常的方式在 RunWorkerCompleted 中公开创建的图像,但它似乎没有工作:
Private Sub FinishDrawingSidebar(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BW_DrawSideBarImage.RunWorkerCompleted
Dim Bmp As BitmapImage = TryCast(e.Result, BitmapImage)
PreviewImage.Source = Bmp
End Sub
我也试过了
Dispatcher.Invoke(Sub() PreviewImage.Source = Bmp)
在 DoWork 和 RunWorkerCompleted 中,但出现相同的错误。如果我只是 return Nothing 而不是 Bmp 那么就没有问题所以我假设 Bmp 是被抱怨的对象。
请让我知道我做错了什么蠢事。谢谢!
只要 BitmapImage 仍可修改,它就会与创建它的线程保持关联。在另一个线程中使用它会抛出你得到的异常。
修复起来很简单,您需要冻结它,使其成为线程安全的。将这行代码添加到您的工作人员:
...
bmp2.EndInit()
bmp2.Freeze(); // <== added
您好,在处理完成后,我无法将在 BackgroundWorker 的 DoWork 处理程序中生成的图像数据分配给图像对象。我收到一条错误消息,指出 "the calling thread cannot access this object because a different thread owns it"。错误行是
PreviewImage.Source = Bmp
我的DoWork处理程序代码如下:
Private Sub QueryForAssociatedData(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BW_DrawSideBarImage.DoWork
Using Context As New MyContext
Try
Dim bmp2 As New BitmapImage
bmp2.BeginInit()
bmp2.StreamSource = New MemoryStream(SidebarImageBytes)
bmp2.EndInit()
'Dispatcher.Invoke(Sub() PreviewImage.Source = bmp2)
e.Result = bmp2
Catch ex As Exception
End Try
End Using
End Sub
我希望能够以通常的方式在 RunWorkerCompleted 中公开创建的图像,但它似乎没有工作:
Private Sub FinishDrawingSidebar(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BW_DrawSideBarImage.RunWorkerCompleted
Dim Bmp As BitmapImage = TryCast(e.Result, BitmapImage)
PreviewImage.Source = Bmp
End Sub
我也试过了
Dispatcher.Invoke(Sub() PreviewImage.Source = Bmp)
在 DoWork 和 RunWorkerCompleted 中,但出现相同的错误。如果我只是 return Nothing 而不是 Bmp 那么就没有问题所以我假设 Bmp 是被抱怨的对象。
请让我知道我做错了什么蠢事。谢谢!
只要 BitmapImage 仍可修改,它就会与创建它的线程保持关联。在另一个线程中使用它会抛出你得到的异常。
修复起来很简单,您需要冻结它,使其成为线程安全的。将这行代码添加到您的工作人员:
...
bmp2.EndInit()
bmp2.Freeze(); // <== added