According to MSDN connect page :
Note When you issue a blocking Winsock call, such as connect , Winsock may have to wait for the network event to complete the call. Winsock makes an emergency wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another Winsock blocking call within APC that interrupted the current Winsock blocking call in the same thread will result in undefined behavior and should never be attempted by Winsock clients.
So, if you want to cancel the call connect, you must do this from another thread:
VOID CALLBACK apc( _In_ ULONG_PTR data)
{
printf("connect canceled by APC\n");
}
DWORD WINAPI cancel_thread_function(void* main_thread_handle)
{
Sleep(500);
if (test_if_connect_is_still_pending())
{
QueueUserAPC(apc, (HANDLE)main_thread_handle, (ULONG_PTR) NULL);
}
return 0;
}
HANDLE mainThread;
DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mainThread, 0, TRUE, DUPLICATE_SAME_ACCESS);
CreateThread(NULL, 0, cancel_thread_function, , 0, NULL);
connect(...);
IMO, EJP solution is the best (non-blocking connectand testing with select).
source
share