我有一个Winforms应用程序,它有一个Winform控件并启动一个线程。 为了捕获Winform控件引发的异常,我实现了ThreadExceptionHandler。 当控件中发生异常时,我想做两件事:记录它并停止线程以便应用程序停止。问题是我无法访问记录器和ThreadExceptionhandler中的线程,因为它是静态的。因此,我无法执行日志记录,更糟糕的是,结束线程。
static void Main()
{
MainForm form = null;
try
{
Application.ThreadException += new ThreadExceptionEventHandler(MainForm.ThreadExceptionHandler);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new MainForm();
Application.Run(form);
}
catch (Exception ex)
{
form.logger.log(ex);
form.thread.Stop();
}
}
和MainForm类:
public partial class MainForm : Form
{
internal MyThread thread;
internal Logger logger = new Logger();
public MainForm()
{
MyForm formThatThrowsAnException = new MyForm();
thread = new MyThread();
thread.Isbackground = false; // prevents app from stopping
}
internal static void ThreadExceptionHandler(object sender, ThreadExceptionEventArgs args)
{
try
{
// log here
// stop thread here
}
catch { }
}
}
}
我试着这样做:
MainForm form = null;
try
{
form = new MainForm();
Application.ThreadException += new ThreadExceptionEventHandler(form.ThreadExceptionHandler);
...
并从异常处理程序方法中删除static关键字,但这不起作用,因为没有调用该方法。
答案 0 :(得分:0)
<强> MyThread的强>
internal static void Stop(){...}
<强>日志强>
internal static void log(){...}
主要形式:
internal MyThread thread;
internal Logger logger = new Logger();
public MainForm()
{
MyForm formThatThrowsAnException = new MyForm();
thread = new MyThread();
thread.Isbackground = false; // prevents app from stopping
}
internal static void ThreadExceptionHandler
(object sender, ThreadExceptionEventArgs args){
try
{
Logger.log(new Exception());
MyThread.Stop();
}
catch { }
}
主要功能:
static void Main()
{
MainForm form = null;
try
{
Application.ThreadException += MainForm.ThreadExceptionHandler;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new MainForm();
Application.Run(form);
}
catch (Exception ex)
{
if (form != null)
{
Logger.log(ex);
MyThread.Stop();
}
}
}