0

我正在使用一个运行 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 窗口中绑定的转换器。

4

1 回答 1

0

错误很明显:

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

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

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

于 2012-08-30T19:12:53.097 回答