我目前正在用托管 C++ 编写一个 winsock 服务器端套接字。创建 LPWSAOVERLAPPED 对象并将其传递给 WSASend 函数后,我看不到在操作完成非阻塞时将其删除的位置(WSASend 返回 SOCKET_ERROR 并且 WSAGetLastError() 返回 WSA_IO_PENDING)。我当前的解决方案是创建一个 System::Threading::WaitHandle,获取指向等待句柄的不安全指针并将其传递给 LPWSAOVERLAPPED 对象下的 hEvent。但是,这会导致不必要的对象创建,因为我并不真正关心发送操作何时完成。另一方面,我需要一个 LPWSAOVERLAPPED 对象以使操作完全无阻塞。有没有人有更好的解决方案来解决这个问题?这是我当前的代码:
void Connectivity::ConnectionInformation::SendData(unsigned char data[], const int length)
{
if (isClosed || sendError)
return;
Monitor::Enter(this->sendSyncRoot);
try
{
LPWSAOVERLAPPED overlapped = OverlappedObjectPool::GetOverlapped();
WaitHandle ^ handle = gcnew ManualResetEvent(false);
IntPtr handlePointer = handle->SafeWaitHandle->DangerousGetHandle();
sendInfo->buf = (char*)data;
sendInfo->len = length;
overlapped->Internal = 0;
overlapped->InternalHigh = 0;
overlapped->Offset = 0;
overlapped->OffsetHigh = 0;
overlapped->Pointer = 0;
overlapped->hEvent = (void*)handlePointer; //Set pointer
if (WSASend(connection, sendInfo, 1, NULL, 0, overlapped, NULL) == SOCKET_ERROR)
{
if (WSAGetLastError() == WSA_IO_PENDING)
{
ThreadPool::UnsafeRegisterWaitForSingleObject(handle, sentCallback, (IntPtr)((void*)overlapped), -1, true);
}
else
{
this->sendError = true;
//The send error bool makes sure that the close function doesn't get called
//during packet processing which could lead to a lot of null reffernce exceptions.
OverlappedObjectPool::GiveObject(overlapped);
}
}
else
{
handle->Close();
sentData((IntPtr)((void*)overlapped), false);
}
}
finally
{
Monitor::Exit(this->sendSyncRoot);
}
}