2011-03-14 62 views
0

是否有任何可能的方法来自动附加所有字符串/等到我选择的文本框(或其他形式)?现在为了在Main类之外的任何类中执行此操作,我必须将其路由到它,然后使用Main类来发布它。C#方便懒惰的异常处理

澄清(改变): 我不再希望只是处理异常。我真的只想从我的程序中的任何地方传递字符串/文本,而不必将它传递给MainWindow。

namespace MyProgram 
{ 
    public partial class MainWindow : Window 
    { 
     Main goes here... 
    } 

} 

namespace People 
{ 
    public class Worker 
    { 
     public void printToLog() 
     { 
      textBoxErrorlog.AppendText("Message...."); 
     } 
    } 
} 

上面的代码将不起作用。我将不得不将字符串返回到MainWindow类并从那里追加(bc textBoxErrorlog不存在于Worker中)。我想跳过这一步,只是从Worker类发布它。

+4

你是什么意思 “所有异常”?你的意思是所有未处理的异常?最简单的方法是不抓住它们,然后你的应用程序将崩溃,你将不得不修复你的bug。 – 2011-03-14 17:10:30

+2

添加代码!告诉我们你在做什么。说“路由到它”并没有画出一幅清晰的图画。 – RQDQ 2011-03-14 17:14:22

回答

4

你的问题很模糊。但是我有一种感觉,你会发现有趣/有用的这些事件:

Application.ThreadException 
AppDomain.CurrentDomain.UnhandledException 

编辑您添加的代码之后:

一般来说它的坏赶上Exception。在你的情况下,我会建议挂钩AppDomain.CurrentDomain.UnhandledException并在该处理程序附加到MainWindow的例外日志文本框。

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 
    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
    { 
     if (!e.IsTerminating) 
     { 
      MainWindow mw = GetRefToTheMainWindowSomehow(); 
      mw.AppendException(e.ExceptionObject); 
     } 
    } 

而且在主窗口:

internal delegate void AppendExceptionDelegate(Exception e); 

    public void AppendException(Exception e) 
    { 
     if (this.InvokeRequired) 
     { 
      this.Invoke(new AppendExceptionDelegate(AppendException), new[] { e }); 
     } 
     else 
     { 
      this._textBox.Text += e.Message; 
     } 
    } 
+0

我更新了我的问题。我正在寻找一种更简单的方式来做事。感谢您的帮助。 – PiZzL3 2011-03-14 23:38:59

+0

我不知道,如果你可以得到比这更简单。由于GUI线程和控件在WinForms中的工作方式,AppendException方法很复杂。 – 2011-03-15 01:02:40

+0

WPF/XAML怎么样?我没有使用WinForms。有没有办法传递一个字符串,而不是所有的异常?从上面的代码看来,我只能在例外情况下使用它。 – PiZzL3 2011-03-15 02:40:59

1

你可以为Log4Net创建一个自定义appender并让它做到这一点。除此之外,您需要捕获异常并将它们编组回到UI线程。

0

您可以利用从AppDomain接线UnhandledException事件并将所有未处理的异常路由到您喜欢的任何地方。

AppDomain currentDomain = AppDomain.CurrentDomain; 
currentDomain.UnhandledException += (sender, args) => { /* Write To Wherever */ }; 

我会建议充实了这一点,使用一个真正的处理程序等,但它给你的想法。