STA线程异常传播

时间:2011-05-02 21:25:52

标签: c# multithreading exception

我有一个必须作为STA运行的函数,我想将其异常传播给调用线程。这是:

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
  }
}

将STA属性置于“MainFunction”上不是一个选项。 我注意到如果我正在使用Task,尝试catch任务join会将异常传播给调用线程,但是我不能指定运行任务作为STA。

问题是如何在例子ablove中将作为STA运行的异常传播到“MainFunction”?

提前致谢。

3 个答案:

答案 0 :(得分:4)

我遵循了Hans的建议,解决方案如下所示,不需要解决任何事件。

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
  }
}

答案 1 :(得分:0)

您需要在等待时保持消息启动并运行。 Thread.Join不是你可以使用的选项,因为它会阻塞你的线程,直到另一个线程终止。 一个非常简单的消息泵是您创建两个名为StaThreadExited和StaThreadExceptionEvent的事件。您可以在事件数组上使用WaitHandle.WaitAny。如果是异常事件,您可以从例如共享变量并在您自己的线程中重新抛出它。我不久前在这里发布了code

此致,   Alois Kraus

答案 2 :(得分:0)

如果线程是STA或MTA,则

无关紧要。未捕获的异常会使您的应用程序崩溃。你不能把它扔到创建你行为不端的线程的线程上,除非你设计一个方法来手动执行:比如捕获,将它存储在某个地方,并通知主线程有错误