I have a WPF Application running on a STA thread that I can't seem to close, the Start and the Stop goes through a singleton class, and the idea is use It wherever I want in my project with Context.Instance.Start()
or Context.Instance.Stop()
the problem is if I try to shutdown _application
as shown in the code below I get an Exception of trying to access an object thant belongs to another thread
public class Context
{
public static Context Instance => _instance ?? (_instance = new Context());
private static Context _instance;
private readonly Thread _thread;
private CustomApplication _application;
private bool _isStarted;
private Context()
{
_thread = new Thread(RunApplication);
_thread.SetApartmentState(ApartmentState.STA);
}
private void RunApplication()
{
_application = new CustomApplication();
_application.Run();
}
private void ShutdownApplication()
{
_application.Shutdown();
_application = null;
}
public void Start()
{
if(!_isStarted)
{
_thread.Start();
_isStarted = true;
}
}
public void Stop()
{
if(!_isStarted)
{
try
{
ShutdownApplication(); // Exception due to _application belongs to _thread
_thread.Abort();
}
catch (ThreadAbortException)
{
}
finally
{
_isStarted = false;
}
}
}
}
Is there a anyway of calling ShutdownApplication
on the still running _thread
or access the object ?