.net 线程c中发生异常时进程未终止#
我有一个System.Timers.Timer,我发现在ElapsedEventHandler中有时会发生异常,但进程没有终止,但执行ElapsedEventHandler的线程在异常发生的地方完全终止。不太好,因为我当时没有意识到这个异常。为什么进程没有终止?如果ElapsedEventHandler中发生异常,如何以最佳方式终止进程 我尝试使用System.Threading.Timer执行类似操作,然后进程终止。 你能解释一下区别吗 完整代码如下:.net 线程c中发生异常时进程未终止#,.net,multithreading,exception,process,terminate,.net,Multithreading,Exception,Process,Terminate,我有一个System.Timers.Timer,我发现在ElapsedEventHandler中有时会发生异常,但进程没有终止,但执行ElapsedEventHandler的线程在异常发生的地方完全终止。不太好,因为我当时没有意识到这个异常。为什么进程没有终止?如果ElapsedEventHandler中发生异常,如何以最佳方式终止进程 我尝试使用System.Threading.Timer执行类似操作,然后进程终止。 你能解释一下区别吗 完整代码如下: class Program {
class Program
{
static public void DoBad()
{
Console.WriteLine("DoBad enter");
string s = "hello";
object o = s;
int i = (int)o; // Ops! Something unexpected happend here... Exception
Console.WriteLine("DoBad exit");
}
static void DoIt1(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("\nDoIt1 enter");
DoBad(); // Process is NOT terminated when excpetion occurs in DoBad, thread just dies quietly but process continues. Why is process not terminated?
Console.WriteLine("DoIt1 exit");
}
static void Test1()
{
System.Timers.Timer t = new System.Timers.Timer(2000);
t.Elapsed += new System.Timers.ElapsedEventHandler(DoIt1);
t.Enabled = true;
}
static public void DoIt2(Object o)
{
Console.WriteLine("\nDoIt2 enter");
DoBad(); // Process terminated when exception occurs in DoBad.
Console.WriteLine("DoIt2 exit");
}
static void Test2()
{
System.Threading.Timer timer = new System.Threading.Timer(DoIt2, null, 0, 2000);
}
static void Main(string[] args)
{
Test1(); // Process NOT terminated when exception occurs in DoBad
// Test2(); // Process terminated when exception occurs in DoBad
// Why is process NOT terminated when running Test1 (but terminated when running Test2)?
// Want process to die. How to do it in best way?
Console.WriteLine("Main Sleep");
System.Threading.Thread.Sleep(11000);
Console.WriteLine("Main Slept");
}
}
/谢谢 这是通过设计完成的,正如您在这里看到的:()
在.NET Framework 2.0及更早版本中,计时器组件捕获并抑制事件处理程序为已过去事件引发的所有异常。此行为可能会在.NET Framework的未来版本中发生更改。
system.threading.timer不会执行此操作,因此会传递异常并终止进程。 如果您想了解该异常,那么您应该捕获它并记录它。
如果希望在主线程中完成所有工作,可以使用invoke/begininvoke:
form1.Invoke((ThreadStart)delegate
{
//do something
});
或者使用Windows.forms.timer(winforms)/System.Windows.Threading.Dispatchermer(WPF)这是通过设计完成的,如您在此处所见:()
在.NET Framework 2.0及更早版本中,计时器组件捕获并抑制事件处理程序为已过去事件引发的所有异常。此行为可能会在.NET Framework的未来版本中发生更改。
system.threading.timer不会执行此操作,因此会传递异常并终止进程。 如果您想了解该异常,那么您应该捕获它并记录它。
如果希望在主线程中完成所有工作,可以使用invoke/begininvoke:
form1.Invoke((ThreadStart)delegate
{
//do something
});
或者使用Windows.forms.timer(winforms)/System.Windows.Threading.DispatcherTimer(WPF)System.Timers.timer就是这样。它将吞咽已用事件处理程序引发的所有异常。要么自己抓住它们,要么喜欢System.Threading.TimerSystem.Timers.Timer就是这样。它将吞咽已用事件处理程序引发的所有异常。要么自己抓住它们,要么选择System.Threading.Timer