0

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 ?

ihisham
  • 248
  • 1
  • 10
  • 1
    `_application.Dispatcher.Invoke(() => _application.Shutdown())` – Clemens Dec 02 '20 at 18:11
  • that actually worked! `_application.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);` – ihisham Dec 02 '20 at 20:13
  • 1
    Take a look at this: [What's wrong with using Thread.Abort](https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort). Also this method is not supported on .NET 5. – Theodor Zoulias Dec 02 '20 at 23:40

0 Answers0