title: Boost::Asio io_context::run Unknown Visual C++ Runtime Error : Debug Error
body: <p>Boost Version : 1.68</p>
  
  <p>C++ Standard : C++17</p>
  
  <p>Development Platform : MSVC 2017</p>
  
  <p>Operating System : Windows 10 Professional</p>
  
  <p>PC Architecture : x64</p>
  
  <p>I am using Boost::Asio to create an asynchronous TCP connection. During first successful connection everything works properly. Due to certain problem it socket break it attempts to re-connect and that time I get the run-time error. Even though I get run-time error the program still is able to receive data.</p>
  
  <p>At first I was attempting to reconnect the socket in my main function's while (infinite) loop (main thread), but I was getting the error.
  I was getting error in </p>
  
  <blockquote>
    <p>D:\vcpkg\installed\x64-windows\include\boost\asio\detail\impl\win_iocp_io_context.ipp</p>
  </blockquote>
  
  <pre><code>size_t win_iocp_io_context::run(boost::system::error_code&amp; ec)
  {
    if (::InterlockedExchangeAdd(&amp;outstanding_work_, 0) == 0)
    {
      stop();
      ec = boost::system::error_code();
      return 0;
    }
  
    win_iocp_thread_info this_thread;
    thread_call_stack::context ctx(this, this_thread);
  
    size_t n = 0;
    while (do_one(INFINITE, ec))
      if (n != (std::numeric_limits&lt;size_t&gt;::max)())
        ++n;
    return n;
  }
  </code></pre>
  
  <p>on line when n = 13</p>
  
  <blockquote>
    <p>while (do_one(INFINITE, ec))</p>
  </blockquote>
  
  <p>I solved the error by adding my connect call in my receive and send handler once they detected connection is broken or socket is down.</p>
  
  <p>Can someone explain why I faced the issue when attempting to reconnect from main thread and the issue got resolved when I tried to reconnect immediately after socket was broken in io_context thread.</p>
  
  <p>I did restart context before I called run after connection was lost and io_context thread exited.</p>
  
  <p>While Loop in my main function :    </p>
  
  <pre><code>while (true)
  {
      fmt::print("Socket Alive : {}\n", as.isSocketAlive());
      while(not as.isSocketAlive() and not as.isConnectionInProcess())
          as.connectSocket();
      if (not as.isSocketAlive())
          continue;
      if (as.isReadComplete())
          as.sendDataSocket(as.getRecievedData());
  }   
  </code></pre>
  
  <p>My Async-Socket Functions :</p>
  
  <pre><code>void AsyncSocket::runContext(void)
  {
      std::atomic_store(std::addressof(this-&gt;contextExitted), false);
      this-&gt;context.run();
      std::atomic_store(std::addressof(this-&gt;contextExitted), true);
  }
  
  void AsyncSocket::restartContext(void)
  {
      if (std::atomic_load(std::addressof(this-&gt;contextExitted)))
          this-&gt;context.restart();
  }
  
  void AsyncSocket::connectSocket(void)
  {
      std::atomic_store(std::addressof(this-&gt;socketAlive), false);
      std::atomic_store(std::addressof(this-&gt;connectionInProcess), true);
      //this-&gt;socket.async_connect(this-&gt;endpoint, std::bind(&amp;AsyncSocket::connectHandler, this, boost::asio::placeholders::error));
      this-&gt;socket.async_connect(this-&gt;endpoint, boost::bind(&amp;AsyncSocket::connectHandler, this, boost::asio::placeholders::error));
      //this-&gt;socket.connect(this-&gt;endpoint, );
      if (this-&gt;context.stopped())
      {
          if (this-&gt;isContextExitted())
              this-&gt;restartContext();
          this-&gt;t = std::thread(&amp;AsyncSocket::runContext, this);
      }
      std::call_once(this-&gt;firstRun, [this]() {
          t = std::thread(&amp;AsyncSocket::runContext, this);
      });
  }
  
  void AsyncSocket::recieveHandler(const boost::system::error_code&amp; ec, std::size_t bytes_transferred)
  {
      fmt::print("In recieve handler, Error Code : {}\nBytes recieved : {}\n", ec.message(), bytes_transferred);
      try
      {
          std::atomic_store(std::addressof(this-&gt;receivingData), false);
          if (ec not_eq boost::system::errc::success)
          {
  #ifdef _DEBUG
              fmt::print("Error in WebSocket::recieveHandler. Error : {0}\n", ec.message());
  #endif // _DEBUG
              LOG_ERROR &lt;&lt; ec.message();
              switch (ec.value())
              {
              case boost::asio::error::eof :
              case boost::asio::error::connection_reset :
              case boost::asio::error::connection_aborted :
              case boost::asio::error::network_reset :
              case boost::asio::error::network_down :
              case boost::asio::error::network_unreachable :
                  if (this-&gt;isSocketAlive() and this-&gt;socket.is_open())
                      this-&gt;socket.close();
                  std::atomic_store(std::addressof(this-&gt;socketAlive), false);
                  this-&gt;connectSocket();// If I comment this line and try to reconnect in my main function (infinite while loop), I get mentioned run-time error
                  return;
              default:
                  break;
              }
  
          }
          else
          {
              this-&gt;readDataQueue.push(std::string(reinterpret_cast &lt;const char *&gt; (this-&gt;readDataBuffer.data()), bytes_transferred));
              std::atomic_store(std::addressof(this-&gt;readComplete), true);
          }
      }
      catch (const std::exception&amp; ex)
      {
  #ifdef _DEBUG
          fmt::print("Error in WebSocket::sendHandler. Error : {0}\n", ex.what());
  #endif // _DEBUG
          LOG_ERROR &lt;&lt; "Exception : " &lt;&lt; ex.what() &lt;&lt; "Data : " &lt;&lt; this-&gt;writeDataQueue.front();
      }
      this-&gt;recieveDataSocket();
  }
  
  
  
  void AsyncSocket::sendHandler(const boost::system::error_code&amp; ec, std::size_t bytes_transferred)
  {
      fmt::print("In send handler, Error Code : {}\nBytes recieved : {}\n", ec.message(), bytes_transferred);
      try
      {
          if (ec not_eq boost::system::errc::success)
          {
  #ifdef _DEBUG
              fmt::print("Error in WebSocket::recieveHandler. Error : {0}\n", ec.message());
  #endif // _DEBUG
              LOG_ERROR &lt;&lt; ec.message();
              switch (ec.value())
              {
              case boost::asio::error::eof:
              case boost::asio::error::connection_reset:
              case boost::asio::error::connection_aborted:
              case boost::asio::error::network_reset:
              case boost::asio::error::network_down:
              case boost::asio::error::network_unreachable:
                  if (this-&gt;isSocketAlive() and this-&gt;socket.is_open())
                      this-&gt;socket.close();
                  std::atomic_store(std::addressof(this-&gt;socketAlive), false);
                  this-&gt;connectSocket();// If I comment this line and try to reconnect in my main function (infinite while loop), I get mentioned run-time error
                  return;
              default:
                  break;
              }
  
          }
          this-&gt;writeDataQueue.pop();
          std::atomic_init(std::addressof(this-&gt;sendingData), false);
          this-&gt;writeSocket();
      }
      catch (const std::exception&amp; ex)
      {
  #ifdef _DEBUG
          fmt::print("Error in WebSocket::sendHandler. Error : {0}\n", ex.what());
  #endif // _DEBUG
          LOG_ERROR &lt;&lt; "Exception : " &lt;&lt; ex.what() &lt;&lt; "Data : " &lt;&lt; this-&gt;writeDataQueue.front();
      }
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/yjKvV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yjKvV.jpg" alt="Run-time Error"></a></p>