我有时会收到此错误:
An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance.
...当我尝试调用 SocketServiceEventArgs.SetBuffer()
我意识到这是因为一个实例只能执行一个操作并且它必须在使用中。但是我再次调用它是因为在客户端先前超时之后,我希望尝试重新发送请求。我不希望关闭此套接字并使用一个新套接字,因为那样的话与客户端的连接就会中断。
但是,我需要做的是在执行此操作之前检查是否有另一个操作已经在进行中,如果是,则终止它,以便我可以再次发送。
我用来发送的代码是
saeaCommunicationObject.AcceptSocket.SendAsync(saeaCommunicationObject)
但更有可能正在进行的是接收
saeaCommunicationObject.AcceptSocket.ReceiveAsync(saeaCommunicationObject))
(saeaCommunicationObject
是一个 SocketAsyncEventArgs
)。
在研究中,我遇到过
AcceptSocket.EndReceive(IAsyncResult 异步结果)
但我不确定这是否正确,而且我也不知道从哪里获得 asyncResult(所以如果这是正确的,我的问题是,这应该来自哪里?)
那么我该怎么做才能检查它是否在进行中(如果是,则终止它)?
编辑
我看过的一个地方建议(但不推荐)使用 CancelIoEx()
使用 P/Invoke - 但是我无法让它工作,而且关于这方面的文档很少。
[DllImport("kernel32.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CancelIoEx(IntPtr hFile);
private void CancelReceive() {
bool result = CancelIoEx(saeaCommunicationObject.AcceptSocket.Handle)
// etc.
}
我得到 result
= false
。我也尝试过 CancelIo()
并且当我得到 result
= true
时,当我尝试调用 >SetBuffer()
.
长话短说
调用 ReceiveAsync()
后套接字正在等待输入以触发 Completed
事件,如何取消此请求?
最佳答案
来自 MSDN:
Returns true if the I/O operation is pending. The SocketAsyncEventArgs.Completed event on the e parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The SocketAsyncEventArgs.Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.
因此,您应该检查 ReceiveAsync
调用的返回值。如果它的 true
订阅 SocketAsyncEventArgs.Completed
事件。如果为假,则立即检查 SocketAsyncEventArgs
以验证结果。
关于c# - SocketAsyncEventArgs - 如何检测正在进行的套接字操作并终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462116/