Search code examples
c#multithreadingexception

STA thread exception propagation


I have a function that must be running as STA, and I want to propagate its exceptions to calling thread. Here it is:

public void ExceptionBePropagatedThroughHere()
{
  Thread thread = new Thread(TheSTAThread);
  thread.SetApartmentState(ApartmentState.STA);
  thread.Start();
  thread.Join();
}

public void MainFunction()
{
  try
  {
    ExceptionBePropagatedThroughHere();
  }
  catch(Exception e)
  {
     //will not hit here
  }
}

Putting STA attribute on "MainFunction" is not an option here. I noticed if I was using Task, try catch on task join will propagate exception to calling thread, however I cannot specify run a task as STA.

The question is how to propagate exception running as STA to "MainFunction" in the example ablove?

Thanks in advance.


Solution

  • I followed Hans' suggestion and the solution looks like below, no events need to be fired.

    private Exception _exception;
    public void ExceptionBePropagatedThroughHere()
    {
      Thread thread = new Thread(TheSTAThread);Thread thread = new Thread(TheSTAThread);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start();
      thread.Join();
      if(_exception != null)
        throw new Exception("STA thread failed", _exception);
    }
    
    private void TheSTAThread()
    {
      try
      {
        //do the stuff
      }
      catch (Exception ex)
      {
        _exception = ex;
      }
    }
    public void MainFunction()
    {
      try
      {
        ExceptionBePropagatedThroughHere();
      }
      catch(Exception e)
      {
         //will not hit here
      }
    }