Click here to Skip to main content
15,890,399 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
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:
C#
_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:
C#
_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.

C#
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    //Show Splash Screen
    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:

C#
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    //Show Splash Screen
    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
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900