My main form takes a long time to create so I added it into my splash form which shows a loading screen. My main form creates its own view model who's properties are databound to a lot of controls. Within the view model constructor, I capture the SynchronizationContext.Current and Thread.CurrentThread via:
_synchronizationContext = SynchronizationContext.Current;
_creationThread = Thread.CurrentThread;
and save that to a variable. For the properties that i know are often updated from a worker thread, I check to see if
Thread.CurrentThread = _creationthread
and if it does not, I use the captured _synchronizationContext to update the property:
_synchronizationContext.Send(delegate
{
SomeProperty = GetData();
}, null);
When the main form is created within the splash form, I get a TargetInvocationException when the property is updated from a worker thread. This is what what my Program.cs file looks like to start the program.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
frmSplash frmS = new frmSplash();
frmS.ShowDialog();
Application.Run(frmS.MainForm);
}
When I don't create the main form in the splash form it works fine. This is what the Program.cs file looks like in that scenario:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
frmSplash frmS = new frmSplash();
frmS.ShowDialog();
Application.Run(new Views.RfrmMain());
}
Clearly something is different in the SynchronizationContext that is created within the view model. But what, why, and how do I resolve this?
Thanks