Search code examples
c++boost-asiowsastartup

boost::asio::io_service throws exception


Okay, I seriously cannot figure this out.

I have a DLL project in MSVC that is attempting to use Asio (from Boost 1.45.0), but whenever I create my io_service, an exception is thrown. Here is what I am doing for testing purposes:

void run()
{
    boost::this_thread::sleep(boost::posix_time::seconds(5));
    try
    {
        boost::asio::io_service io_service;
    }
    catch (std::exception & e)
    {
        MessageBox(NULL, e.what(), "Exception", MB_OK);
    }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        boost::thread thread(run);
    }
    return TRUE;
}

This is what the message box shows:

winsock: WSAStartup cannot function at this time because the underlying system it uses to provide network services is currently unavailable

Here is what MSDN says about it (error code 10091, WSASYSNOTREADY):

Network subsystem is unavailable. This error is returned by WSAStartup if the Windows Sockets implementation cannot function at because the underlying system it uses to provide network services is currently unavailable. Users should check: That the appropriate Windows Sockets DLL file is in the current path. That they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded. The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.

Yet none of this seems to apply to me (or so I think).

Here is my command line:

/O2 /GL /D "_WIN32_WINNT=0x0501" /D "_WINDLL" /FD /EHsc /MD /Gy /Fo"Release\" /Fd"Release\vc90.pdb" /W3 /WX /nologo /c /TP /errorReport:prompt

If anyone knows what might be wrong, please help me out! Thanks.


Solution

  • Microsoft recommends not to call WSAStartup from DllMain, so your best bet would be to create an IO thread elsewhere.

    The WSAStartup function typically leads to protocol-specific helper DLLs being loaded. As a result, the WSAStartup function should not be called from the DllMain function in a application DLL.