c#中的事件处理程序的顶级异常处理 [英] top-level exception handling with event handlers in c#

查看:237
本文介绍了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#中的事件处理程序的顶级异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆