使用ConcurrentDictionary但导致Thread错误

时间:2012-08-30 16:02:23

标签: wpf vb.net multithreading

我正在使用一个运行Tasks.Parallel的backgroundworker。遵守守则:

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窗口中的转换器。

1 个答案:

答案 0 :(得分:0)

错误很明显:

您正在使用一个“属于”Bgw / Parallel代码中的GUI线程的DependencyObject。

字典并不是并行化时的唯一问题。

另外:将一个CompletedHandler添加到bgw进行错误处理总是一个好习惯。