我有一个工作线程,当它终止时,它会发出一个事件信号。然后将此事件编组到主线程以通知它工作线程的终止。当工作线程遇到未处理的异常时,我希望这个异常由主线程的错误处理系统来处理。因此,工作线程设置一个属性指示其意外终止,并将异常保存在另一个属性中,然后发出事件信号并退出。
将事件编组到主线程后,我想抛出一个新异常,并将原始异常设置为内部异常。我的问题是:这个新异常的类型应该是什么?对于这种情况是否有特定的 System.somethingException,我应该为这种特定情况设计自己的 Exception 类,还是认为抛出带有适当消息的标准 System.Exception 是合适的?
C#-伪代码:
class MyThread
{
public TerminationState Termination { get; private set; }
public Exception UncaughtException { get; private set; }
public delegate void ThreadTerminatedDelegate(MyThread thread);
public event ThreadTerminatedDelegate ThreadTerminated;
private void run()
{
try
{
doSomeWork();
}
catch(Exception e)
{
UncaughtException = e;
Termination = TerminationState.AbortOnException;
ThreadTerminated(this);
return;
}
Termination = TerminationState.NormalTermination;
ThreadTerminated(this);
}
}
class MainThread
{
private MyThread myThread = new MyThread();
private void run()
{
myThread.ThreadTerminated += handleTermination;
myThread.Start();
}
private void handleTermination(MyThread thread)
{
if (InvokeRequired)
{
MyThread.ThreadTerminatedDelegate cb = new MyThread.ThreadTerminatedDelegate(handleTermination);
BeginInvoke(cb, new object[] { thread });
}
else
{
if (thread.Termination == TerminationState.AbortOnException)
{
if (isFatal(thread.UncaughtException))
throw new Exception("", thread.UncaughtException); //what to do here?
else
fixTheProblem();
}
else
{
//normal wrapping up
}
}
}
}