顶级的例外在C#与事件处理程序处理 [英] top-level exception handling with event handlers in c#

查看:121
本文介绍了顶级的例外在C#与事件处理程序处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我问自己,关于异常处理和事件处理器的一些问题,我希望你们当中有些人给我一些帮助。

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

我将开始解释,我想在我的C#应用​​程序来实现的:

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

我有一个最高级的方法(让调用它的主要方法)。此方法调用异步方法(至极被称为连接),它连接到一个FTP服务器。

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.

我能做些什么,使这些异常,由最高级别的方法beeing抓?我不想处理回调这些异常。

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.

推荐答案

看看如何BackgroundWorker的涉及这一点:唯一的例外是传播到完成事件处理程序

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

我假设你有某种形式传递到/从委托,这就是你可以添加这样一个属性State对象。你将不得不捕获所有异常的线程,在最外面的范围。但处理仅仅意味着一起传递给它。

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.

有对于RunWorkerCompleted事件的标准模式,请参阅这个MSDN页面

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

这篇关于顶级的例外在C#与事件处理程序处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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