STA Thread Exception Pass

I have a function that should work like an STA, and I want to propagate its exceptions to call the stream. There he 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
  }
}

Including the STA attribute in "MainFunction" is not an option here. I noticed that if I used Task, try catch on task join will throw the exception to the calling thread, however I cannot specify the task start as STA.

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

Thanks in advance.

+3
source share
3 answers

I followed Hans proposal, and the solution seems to be lower, 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
  }
}
+4
source

, , . Thread.Join - , , , . , , StaThreadExited StaThreadExceptionEvent. WaitHandle.WaitAny . , , . . .

,

0

, STA MTA. . , , : , , - ,

0

All Articles