So I understand that you are only allowed to access a UI control from the thread it was created on, but I am getting an error complaining about the line 'this.Close()'. What I am trying to do is start a thread that opens a splash screen with an OpenTK animation.
ERROR: "The calling Thread cannot access this object because a different thread owns it."
Here is the code:
public MainWindow()
{
InitializeComponent();
closeSplashBool = false;
Thread t = new Thread(() =>
{
openSplash = new SplashScreen();
openSplash.Show();
}
);
t.SetApartmentState(ApartmentState.STA);
t.Start();
///
/// Long running task
///
closeSplashBool = true;
}
The only line of code in the constructor for SplashScreen is InitializeComponents(). Here is my animation function for the SplashScreen class (which controls when the splash screen is closed):
private void splashControl_Paint(object sender, PaintEventArgs e)
{
//make sure our GL control has loaded
if (!loaded)
return;
if (animCount <= 0 )
{
Thread.Sleep(200);
if (MainWindow.closeSplash)
this.Close(); //program crashes on this line
}
else if (animCount < 3.75 && animCount >=2.75)
{
animCount -= .2f;
System.Threading.Thread.Sleep(1);
}
else if (animCount < 2.75)
{
animCount -= .07f;
System.Threading.Thread.Sleep(5);
}
else
{
animCount -= .7f;
System.Threading.Thread.Sleep(1);
if (animCount < 0)
animCount = 0;
}
Render();
}
I made a 'new' Splash Screen in Thread 't', so I figured calling 'this.Close()' would not have any access violations. My question is why am I getting this access violation? I have tried replacing 'this.close' with 'Dispatcher.InvokeShutdown' on suggestions from others, but then the Splash Screen never went away.