如何中止套接字的BeginReceive()? [英] How to abort socket's BeginReceive()?

查看:703
本文介绍了如何中止套接字的BeginReceive()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当然, BeginReceive()将永远如果没有数据结束。
MSDN 表明,调用关闭()将中止 BeginReceive()

Naturally, BeginReceive() will never end if there's no data. MSDN suggests that calling Close() would abort BeginReceive().

但是,调用关闭()插座上也执行的Dispose()就可以了,因为想通了在<一个href=\"http://stackoverflow.com/questions/3601521/c-socket-close-should-i-still-call-dispose/3601548#3601548\">this大ansewr ,因此 EndReceive(),因为对象是已经部署会抛出一个异常(和它呢!)。

However, calling Close() on the socket also performs a Dispose() on it, as figured out in this great ansewr, and consequently EndReceive() would throw an exception because the object is already disposed (and it does!).

我该如何操作?

推荐答案

看起来这是由(很愚蠢)的设计。你必须有此异常抛出和捕获在code。

It seems like this is by (the very dumb) design. You must have this exception thrown and caught in your code.

MSDN看起来沉默它确实是,但如果你看看另一个异步套接字方法的文档, BeginConnect (),这里是我们发现:

MSDN looks silent about it indeed, but if you look at the documentation of another asynchronous socket method, BeginConnect(), here's what we find:

要取消挂起的调用
  BeginConnect()方法关闭
  插座。当Close()方法是
  而所谓的异步操作
  在进步,回调提供
  到BeginConnect()方法是
  调用。随后调用
  EndConnect(IAsyncResult的)方法
  抛出的ObjectDisposedException到
  指示操作已
  取消。

To cancel a pending call to the BeginConnect() method, close the Socket. When the Close() method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect() method is called. A subsequent call to the EndConnect(IAsyncResult) method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

如果是做了BeginConnect的正确方法,它可能是因此对于BeginReceive为好。这无疑是对微软的异步API的一部分,一个贫穷的设计,因为让用户一定抛出和捕获异常作为正常流量会得罪调试程序的一部分。你真的没有办法等待,直到操作完成,由于关闭()是在第一时间完成它。

If it is the proper way of doing for BeginConnect, it is probably so for BeginReceive as well. This is certainly a poor design on the part of Microsoft's async API, because making the user necessarily throw and catch exception as a part of a normal flow would annoy the debugger. You have really no way to "wait" until the operation is completed, because Close() is what completes it in the first place.

这篇关于如何中止套接字的BeginReceive()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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