-1

我正在扩展一个 .NET 3.5 应用程序,其基础由其他人奠定,并且在命名空间中添加了成员​​变量My

Namespace My
    Private connection As SqlClient.SqlConnection
    Friend appSession As SomeCustomNamespace.clsSession
    ' and a few more others...
End Namepace

我有一些表格并在那里进行处理。如果我以标准方式(OnClick ...)运行代码,则两个成员变量都有它们的值。如果我将相同的代码移至BackgroundWorker并通过 启动RunWorkerAsync(),则第一个变量具有值,但第二个变量为Nothing(null)。

是什么导致了问题?如何纠正或解决此问题?(My.Application.appSession必须设置,因为许多方法都引用它。)

(是否有机会在使用这种全局变量实现的应用程序中使用后台工作人员作业?)

4

1 回答 1

0

经过一些研究,我决定将My.Application作为参数传递给BackgroundWorker.Run()BackgroundWorker_DoWork()执行接收参数的浅拷贝返回给My.Application. 这样我就得到了My.Application后面的内容。

Private Sub StartBackgroundWork() 
    Me.BackgroundWorker.RunWorkerAsync(My.Application)
End Sub

Private Sub BackgroundWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) _
        Handles BackgroundWorker.DoWork

    My.Application.ShallowCopyFrom(e.Argument)

    'start work here...
End Sub

和我基于这个 StackOverflow 答案创建的ShallowCopyFrom()方法。在 VB 中,必须将其放入代码模块中(使用Add Module...命令,而不是Add Class...):

Imports System.Reflection

Module CompilerExtensionsModule

<System.Runtime.CompilerServices.Extension> _
<System.ComponentModel.Description("Performs shallow copy of fields of given object into this object based on mathing field names.")> _
Public Sub ShallowCopyFrom(Of T1 As Class, T2 As Class)(ByRef obj As T1, ByRef otherObject As T2)
    Dim srcProps As Reflection.PropertyInfo() =
        otherObject.[GetType]().GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.[Public] Or Reflection.BindingFlags.GetProperty)

    Dim destProps As Reflection.PropertyInfo() =
        obj.[GetType]().GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.[Public] Or Reflection.BindingFlags.SetProperty)

    For Each [property] As Reflection.PropertyInfo In srcProps
        Dim dest = destProps.FirstOrDefault(Function(x) x.Name = [property].Name)
        If Not (dest Is Nothing) AndAlso dest.CanWrite Then
            dest.SetValue(obj, [property].GetValue(otherObject, Nothing), Nothing)
        End If
    Next

    Dim srcFields As Reflection.FieldInfo() =
        otherObject.[GetType]().GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public)

    Dim destFields As Reflection.FieldInfo() =
        obj.[GetType]().GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public)

    For Each [field] As Reflection.FieldInfo In srcFields
        Dim dest = destFields.FirstOrDefault(Function(x) x.Name = [field].Name)
        If Not (dest Is Nothing) Then
            dest.SetValue(obj, [field].GetValue(otherObject))
        End If
    Next

End Sub

End Module
于 2013-09-23T13:00:42.100 回答