C#中不能访问一个释放的对象 [英] c# cannot access a disposed object

查看:876
本文介绍了C#中不能访问一个释放的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出一个服务器/客户端应用程序。

I am making an server/client application.

我设置服务器套接字为监听,并设置BeginAccept()方法。 而当我关闭服务器套接字(Socket.Close())关闭服务器, 一个例外,从BeginAccept()方法的异步回调方法抛出。 我检查异常,我发现除了说我:

I set server socket to listening, and set BeginAccept() method. And when I closed server socket (Socket.Close()) to turn off server, an exception thrown from BeginAccept() method's async callback method. I inspected exception, and I found the exception saying me this:

信息无法访问名为一个释放的对象 System.Net.Sockets.Socket。 对象名称:System.Net.Sockets.Socket字符串

Message "Cannot access a disposed object named "System.Net.Sockets.Socket". Object name: "System.Net.Sockets.Socket"." String

在我看来,这仅仅是这样的:当我打电话处置插座 Socket.Close()方法,但回调之前没有发布 插座关闭。

In my opinion, this is just this: "The socket disposed when I call Socket.Close() method, but the callback did not released before the socket closed."

我没有在网上搜索一下,发现这不是错误,但是一个设计例外,beginaccept被取消了。

i did search on the net and found this is not an error but a designed exception as beginaccept was cancelled.

我的问题如何处理这个excepton?是因为它需要有什么样的处理?

my question how do i handle this excepton? what processing there needs to be for it?

感谢。

我只是打算把它作为一个正常的事件:

im just going to treat it as a normal event:

      OnNetworkEvents eventArgs = new OnNetworkEvents(false, "Ready", e.Message);
      OnUpdateNetworkStatusMessage(this, eventArgs);

任何意见仍然是值得欢迎的。

any comments are still welcome.

推荐答案

如果你不关心异常(即它不是一个例外,这是正常的工作程序,发生的每一次),你可以忽略/ SUP preSS它。 (正如只要它不会发生在一个情况,指示真实误差)

If you don't care about the exception (i.e. it's not an "exception", it's the normal operating procedure and happens every time), you can just ignore/suppress it. (Just as long as it won't happen in a situation that indicates a real error)

。这样,你能保证不存在任何悬而未决的读取插座上,并不会得到异常(但这意味着它会挂起约下去,直到接收到另一个包 - 当然这可能永远不会发生)。

If you want to suppress it more tidily, then you can set a flag that tells your callback that it should shut down, and have the callback actually do the closing/disposing of the socket. That way you can guarantee that there are no pending reads on the socket and won't get the exception (but this means it will hang about indefinitely, until another packet is received - which of course may never happen).

如果你是在通信链路两端的控制,那么你可以发送一个明确的关机的消息,告诉客户端的连接应该关闭(这当然可以在回调应用时,该消息被接收)。

If you are in control of both ends of the communications link, then you can send an explicit "shutdown" message that tells the client that the connection should be closed (and this can of course be applied in the callback when the message is received).

(不过,我很想听听是否有人已经找到了更好的解决方案,因为我有一个UDP通讯科实施了类似的情况)

(But I'd love to hear if anyone else has found a better solution as I have a similar situation with a UDP comms implementation)

这篇关于C#中不能访问一个释放的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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