在处理.NET(GUI)事件功能异常没有过多的样板?样板、异常、事件、功能

2023-09-07 08:42:03 作者:雪落成殇

注:我不经常做.NET编程。通常我做本土/ MFC,所以我有点失落,如何做到这一点适当的C#的上下文中。

Note: I don't do .NET programming regularly. Normally I do native/MFC, so I'm a bit lost as how to do this properly in the context of C#.

我们正在显示在本地的MFC应用程序的情况下.NET控件。这意味着GUI线程是一个本地线程调用到.NET控件的WndProc。 (嗯,至少据我可以告诉。)

We're displaying .NET control in the context of a native MFC application. That means the GUI thread is a native thread calling into the WndProc of the .NET control. (Well, at least as far as I can tell.)

很显然,我们的没有的想从我们(GUI)的事件处理程序抛出异常,因为没有合适的处理程序下调用堆栈会赶上他们。

Obviously, we do not want to throw exceptions from our (GUI) event handlers, as there is no proper handler down the call stack that would catch them.

据我所知道的,溶液(S)与的AppDomain / UnhandledExceptionEventHandler 没有意义的本机MFC应用程序。 (请纠正我,如果我错了。)

As far as I can tell, the solution(s) with AppDomain / UnhandledExceptionEventHandler do not make sense in a native MFC application. (Please correct me if I'm wrong.)

于是回了一个问题:如何才能避免有一个try / catch块添加到C#的控制code每个事件处理程序?有一些地方(System.Forms ... Control.WndProc也许?),在那里我可以捕获所有.NET异常,只是显示给用户一个错误对话框?

So back to the question: How can I avoid having to add a try/catch block to each event handler of the C# control code? Is there some place (System.Forms...Control.WndProc maybe?) where I can catch all .NET exceptions and just display an error dialog to the user?

推荐答案

您可以通过使用功能性的方法减少样板code。写一个函数是这样的:

You can reduce boilerplate code by using a functional approach. Write a function like this:

public class Util
{
    public static void SafeCall(Action handler)
    {
      try
      {
           handler();
      }
      catch(Exception ex)
      {
         // process ex here
      }
}

和重用它在每一个你的GUI事件处理:

And reuse it in every of your GUI event handlers:

void MyEvent(object sender, EventArgs e)
{
    Util.SafeCall(()=>NameOfYourHandlerMethod(sender,e));
};

void MyEvent(object sender, EventArgs e)
{
    Util.SafeCall(
    delegate
    {
      // enter code here
    });
};

这可能需要一些额外的工作来获得发件人/ EventArgs的参数,你想要的方式,但你应该明白了吧。

This might need some additional work to get the sender/EventArgs parameters the way you want them, but you should get the idea.