The information in this article applies to:
SYMPTOMS
A multi-threaded application that uses MFC's socket classes encounters a
message box or debug output line that contains an error message similar to
the following: For Visual C++ 4.0:
CAUSE
Most frequently, this problem is due to the sharing of CSocket objects
between multiple threads.
This assertion failure occurs because the CSocket object was either created
or accepted in the context of another thread. The socket notification
window was created in a different thread, and the m_hSocketWindow for the
current thread is NULL, thus the assertion failure.
RESOLUTION
As already mentioned, a CAsyncSocket object should be used only in the
context of a single thread. If you need to switch the thread that is
accessing a SOCKET connection with another thread, then you should use a
separate CAsyncSocket object in each thread, and use the Detach and Attach
functions to attach the CAsyncSocket object to the SOCKET handle in the
thread that is about to use the socket. Use this sequence:
NOTE: One concern often arises that socket notification messages might be lost between the time the call to Detach() is made and the subsequent call to Attach() is made. This is not a concern because of the way socket notifications are handled. The implementation of CAsyncSocket::Attach() makes a call to WSAAsyncSelect to enable notifications. As mentioned in the documentation for WSAAsyncSelect, if any socket noficiations were already pending for the SOCKET, they will be re-posted. MORE INFORMATIONTo Accept a socket in the context of one thread and then begin using it in the context of another thread, you need to be sure to detach the CAsyncSocket object in the first thread and attach a different CAsyncSocket object in the second thread. The following code snippet shows how to do it. Code Sample
REFERENCESMFC Technical Note #2 - Although this technical note does not directly address the CAsyncSocket class, it does discuss the mapping of handles to objects. The relationship between a SOCKET handle and a CAsyncSocket object is maintained in much the same way. Additional query words:
Keywords : kbcode kbMFC kbVC kbWinsock |
Last Reviewed: August 5, 1999 © 2000 Microsoft Corporation. All rights reserved. Terms of Use. |