c#中的事件处理程序的顶级异常处理

编程入门 行业动态 更新时间:2024-10-07 14:26:10
本文介绍了c#中的事件处理程序的顶级异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在问自己一些关于异常处理和事件处理程序的问题,希望有人能给我一些帮助。

我将开始解释一下想要在我的c#应用程序中实现:

我有一个顶级方法(可以称之为主要方法)。该方法调用一个异步方法(即connect),它连接到FTP服务器。

一个EventHandler对象与此连接相关联,一个回调方法在连接成功时调用。

我想处理在整个过程中可以启动的异常。所以我想在顶级方法中抓住它。它适用于由connect方法(在顶层方法中调用)引发的异常。 但是,它不适用于在回调方法中调用的异常:顶级方法不能捕获它们,执行失败。

我做这些例外是由顶级方法捕获的?我不想在回调中处理这些异常。

解决方案

看看Backgroundworker如何处理这个问题:异常传播到Completed事件处理程序。

我假设你有某种形式的State对象被传递给/从委托,这就是你可以添加这样一个属性。并且你将必须捕获线程中最外层的所有异常。但是处理只是意味着传递它。

RunWorkerCompleted事件有一个标准模式,请参阅此MSDN页面。

I am currently asking myself some questions about exception handling and eventhandlers, and i hope some of you will give me some help.

I will start to explain what i would like to achieve in my c# application:

I have a top-level method (lets call it the main method). This method calls an asynchronous method (wich is called connect), which connect to a FTP server.

An EventHandler object is associated to this connection, and a "callback" method is called when the connection is successful.

I want to handle exceptions that can be launched during the whole process. So i would like to catch it in the top level method. It works fine for exceptions launched by the connect method (which is called inside the top level method). However, it does not work for exceptions called inside the "callback" method: the top level method does not catch them and the execution fails.

What can I do to make these exceptions beeing caught by the top level method ? I don't want to handle these exceptions in the callback.

解决方案

Take a look at how the Backgroundworker deals with this: the Exception is propagated to the Completed event handler.

I assume you have some form of State object that is passed to/from the delegate, that's where you can add such a property. And you will have to catch all exceptions in the thread, at the outermost scope. But 'handling' just means passing it along.

There is a standard pattern for the RunWorkerCompleted event, see this MSDN page.

更多推荐

c#中的事件处理程序的顶级异常处理

本文发布于:2023-11-05 10:33:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   事件   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!