After disposing async socket (.Net) callbacks still get called

前端 未结 1 1732
抹茶落季
抹茶落季 2020-12-21 21:41

I feel, that I am misunderstanding something about async sockets in .Net. The situation is as follows : I have 1 async socket client and 1 async socket server. They communic

相关标签:
1条回答
  • 2020-12-21 22:24

    No, this is correct -- the callback you specify in a Begin... operation will always be called, even if you close the socket (if you close the socket, it will be called because of that). You should be catching the ObjectDisposedException you get on the EndAccept and then return without further action. Closing/disposing a socket/listener is the only way to cancel an asynchronous operation on it. (EndAccept can also produce SocketException, which should be handled normally.)

    Using a flag you maintain yourself to check if the listener is still available is asking for trouble, because you're introducing shared state that needs to be synchronized (volatile reads and the like). You can easily introduce race conditions that way. The listener already maintains such a flag for you internally, which it uses to throw ObjectDisposedException, so I'd just use that. It's true that under normal circumstances catching ObjectDisposedException is a possible sign of a coding error (since you're supposed to know when an object is disposed), but with asynchronous code it's pretty standard.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题