After some research I decided to pass My.Application
as argument to BackgroundWorker.Run()
and in BackgroundWorker_DoWork()
perform shallow copy of received parameter back to My.Application
. Thus I got the content of My.Application
back.
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
and ShallowCopyFrom() method I created based on this StackOverflow answer. In VB, it must be put into code module (use Add Module... command, not 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