分享

CSocket对象不能在线程之间传递

 追逐四叶 2019-06-29

csocket对象不能在线程之间传递,如果传递,就可能引发断言ASSERT(pState->m_hSocketWindow != NULL);

csocket对象不能直接在线程之间传递,如果确实需要这样的功能,就用Detach函数取出SOCKET句柄来传递,收到句柄的线程再Attach句柄到本地创建的csocket对象

如下面分析:

CSocket断言错误:ASSERT(pState->m_hSocketWindow != NULL);

起因:在套接字处于连接或者发送状态时,试图关闭套接字,于是在这个断言语句处发生中断。

原因分析::

微软官方解释如下:http://support.microsoft.com/kb/140527/en-us

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.

明白了,我就是跨线程使用CSocket,结果。。。。

解决方案:

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:

1. Use Detach() to detach the CAsyncSocket object from the SOCKET handle in the thread that is currently using the CAsyncSocket object.
2. Use Attach() to attach a different CAsyncSocket object to the SOCKET handle while in the context of the MFC UI thread in which you wish to begin accessing the SOCKET connection.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多