gpt4 book ai didi

c# - System.Timers.Timer Elapsed 库中的异常处理

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:37 25 4
gpt4 key购买 nike

我想在我的 WPF 应用程序中处理发生的 System.Timers.Timer 已用异常(在我的 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();
}
}

最佳答案

异常在另一个线程上抛出(根据您对 Timing.Timer 的选择)。

在 1 个程序集内尝试此操作:您也无法捕捉到它。它在 DLL 中并不重要。

您只能通过重新思考问题并选择其他解决方案来解决此问题。

关于c# - System.Timers.Timer Elapsed 库中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12582598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com