我想在我的 WPF 应用程序中处理发生的 System.Timers.Timer elapsed 异常(在我的 DLL 库中)。但我无法做到这一点。它抛出我的 DLL 库,应用程序将崩溃......有人知道我该如何解决这个问题吗?
这是我的代码:
public partial class MainWindow : Window
{
MyClass _myClassInstance = null;
public MainWindow()
{
InitializeComponent();
try
{
_myClassInstance = new MyClass();
}
catch(Exception ex)
{
//Here i would like to receive the exception
//But it never goes in there
MessageBox.Show(ex.Message);
}
}
}
public class MyClass
{
private System.Timers.Timer _timer = null;
public MyClass()
{
_timer = new Timer();
_timer.Interval = 2000; //2 Seconds
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
ConnectTo();
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//If timer is elapsed I have to raise an exception
throw new Exception("It's taking longer than expected. Progress cancelled!");
}
private void ConnectTo()
{
//Just an example implementation
//Do something!!
//Connect to SerialPort and wait for correct response
//If connected than
_timer.Stop();
}
}