我有一个必须以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,请尝试捕获任务联接将异常传播到调用线程,但是我无法指定将任务作为STA运行。
问题是如何在示例ablove中将以STA运行的异常传播到“MainFunction”?
提前致谢。
最佳答案
我遵循了汉斯的建议,解决方案如下所示,无需触发任何事件。
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
}
}