经过一些研究,我决定将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