相关疑难解决方法(0)

C#事件处理程序应该是异常安全的吗?

假设一个事件有多个处理程序,如果任何事件处理程序抛出异常,则不执行其余处理程序.

这是否意味着事件处理程序永远不应该抛出?

.net c#

20
推荐指数
3
解决办法
7247
查看次数

异步命令模式 - 异常处理

我正在为客户端/服务器应用程序中的"客户端"类实现异步命令模式.我以前做过一些套接字编码,我喜欢他们在Socket/SocketAsyncEventArgs类中使用的新异步模式.

我的异步方法如下所示:public bool ExecuteAsync(Command cmd);如果执行挂起则返回true,如果同步完成则返回false.我的问题是:即使出现异常,我是否应该始终调用回调(cmd.OnCompleted)?或者我应该从ExecuteAsync中抛出异常吗?

如果您需要,可以在这里找到更多细节.这类似于使用SocketAsyncEventArgs,但是我的类被称为SomeCmd而不是SocketAsyncEventArgs.

SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!");
cmd.OnCompleted += this.SomeCmd_OnCompleted;
this.ConnectionToServer.ExecuteAsync(cmd);
Run Code Online (Sandbox Code Playgroud)

与Socket类一样,如果需要与回调方法(在本例中为SomeCmd_OnCompleted)进行协调,则可以使用ExecuteAsync的返回值来了解操作是否挂起(true)或操作是否同步完成.

SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!");
cmd.OnCompleted += this.SomeCmd_OnCompleted;
if( this.ConnectionToServer.ExecuteAsync(cmd) )
{
    Monitor.Wait( this.WillBePulsedBy_SomeCmd_OnCompleted );
}
Run Code Online (Sandbox Code Playgroud)

这是我的基类的大大简化版本,但您可以看到它的工作原理:

class Connection
{
    public bool ExecuteAsync(Command cmd)
    {
        /// CONSIDER: If you don't catch every exception here
        /// then every caller of this method must have 2 sets of
                /// exception handling:
        /// One in the handler of …
Run Code Online (Sandbox Code Playgroud)

.net c# design-patterns exception-handling

3
推荐指数
1
解决办法
9318
查看次数

标签 统计

.net ×2

c# ×2

design-patterns ×1

exception-handling ×1