I have used John's solution and it worked fine for most of the cases. However, in certain situations, the _thread.Abort()
call causes the application to simply crash, without any exceptions. Looking it up, it appears to be very bad practice to use Thread.Abort()
, as is killing a thread (see this, this, this, this and many other online), so as others have said, DO NOT USE Thread.Abort()!
Here's a solution that works perfectly:
public static void CloseForm()
{
// Loop for a maximum of 100ms if the screen hasn't yet been loaded.
for (var i = 0; i < 100; i++)
{
if (loadingScreenForm != null && loadingScreenForm.IsHandleCreated)
{
break;
}
Thread.Sleep(1);
}
// Don't try to close if it is already closed.
// If the screen form is still null after waiting, it was most likely already closed.
if (loadingScreenForm != null && loadingScreenForm.IsHandleCreated)
{
loadingScreenForm.Invoke(new CloseDelegate(CloseFormInternal));
}
}
The specifics of my code require that I check whether the handle has been created but you might be able to do without it. In the case where our situation occurs, this will add an overhead of 100ms to the code. You can tweak it if you feel like a tenth of a second is somehow too much.
I know it's quite late but hopefully it will help someone having the same issue in the future.