我正在使用一个运行 Tasks.Parallel 的后台工作人员。遵循代码:
Public Class SlidertoCanvasBlackWhite
Implements IValueConverter
Dim li As New Concurrent.ConcurrentDictionary(Of Integer, ImageBrush)
Public Sub New()
Dim bw As New ComponentModel.BackgroundWorker
AddHandler bw.DoWork, AddressOf bwworkmain
bw.RunWorkerAsync()
'For i = 0 To 1535
' ' bw.RunWorkerAsync(i)
'Next
End Sub
Private Sub bwworkmain(sender As Object, e As ComponentModel.DoWorkEventArgs)
Dim c As New SlidertoSolidColorBrush
Tasks.Parallel.For(0, 1535, Sub(i)
GetImageBrush(i, CType(c.Convert(i, Nothing, Nothing, Nothing), SolidColorBrush).Color())
End Sub)
End Sub
Private Sub GetImageBrush(ByVal i As Integer, ByVal c As Color)
li.TryAdd(i, BlackWhiteColorGenerator(c))
End Sub
Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If li.ContainsKey(value) Then
Try
Return li(value)
Catch ex As Exception
Return Nothing
End Try
Else
Try
Dim c As New SlidertoSolidColorBrush
Dim z As ImageBrush = BlackWhiteColorGenerator(
CType(c.Convert(value, Nothing, Nothing, Nothing), SolidColorBrush).Color)
Try
li.TryAdd(value, z)
Return z
Catch ex As Exception
Return li(value)
End Try
Catch ex As Exception
Return Nothing
End Try
End If
End Function
Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
Private Function BlackWhiteColorGenerator(ByVal Value As Color) As ImageBrush
'
'Code for Returns ImageBrush
End Function
End Class
我得到的错误是:Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.
我正在使用线程安全字典,即 ConcurrentDictionary,请你告诉我错误在哪里。而且这个类是一个在 WPF 窗口中绑定的转换器。