<p>Ok, I have a strange exception thrown from my code that's been bothering me for ages.</p>

<pre><code>System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall
   at System.Net.Sockets.Socket.Accept()
   at System.Net.Sockets.TcpListener.AcceptTcpClient()
</code></pre>

<p>MSDN isn't terribly helpful on this : <a href="http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx</a> and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. </p>

<p>I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it.</p>

<p>The code runs in a separate background thread, the method starts :</p>

<pre><code>public virtual void Startup()
    {
     TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port));    
        serverSocket.Start();
</code></pre>

<p>then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically:</p>

<pre><code>   while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here
    {
         connectionHandler = new ConnectionHandler(socket, mappingStrategy);
         pool.AddJob(connectionHandler);
    }
  }
</code></pre>

<p>From there, the <code>pool</code> has it's own threads that take care of each job in it's own thread, separately.</p>

<p>My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? </p>

<hr>

<p>Well, I do think some other thread is closing the socket, but it's certainly not from my code. 
What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. </p>

<p>Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?</p>

[{'answer_id': 34373, 'author': 'TimK', 'author_id': 2348, 'author_profile': 'https://Stackoverflow.com/users/2348', 'pm_score': 7, 'selected': True, 'text': '<p>Is it possible that the serverSocket is being closed from another thread?  That will cause this exception.</p>\n'}, {'answer_id': 261393, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>This could happen on a <code>serverSocket.Stop()</code>. Which I called whenever <code>Dispose</code> was called.</p>\n\n<p>Here is how my exception handling for the listen thread looked like:</p>\n\n<pre><code>try\n{\n    //...\n}\ncatch (SocketException socketEx)\n{    \n    if (_disposed)\n        ar.SetAsCompleted(null, false); //exception because listener stopped (disposed), ignore exception\n    else\n        ar.SetAsCompleted(socketEx, false);\n}\n</code></pre>\n\n<p>Now what happened was, every so often the exception would occur before <code>_disposed</code> was set to true. So the solution for me was to make everything thread safe.</p>\n'}, {'answer_id': 7204070, 'author': 'blogga', 'author_id': 913972, 'author_profile': 'https://Stackoverflow.com/users/913972', 'pm_score': 2, 'selected': False, 'text': "<p>Same here!\nBut i figured out, that the ReceiveBuffer on 'server-side' was flooded from the clients!\n(In my case a bunch of RFID-Scanners, who kept spamming the TagCode, instead of stop sending until next TagCode arrives)</p>\n\n<p>It helped to raise the ReceiveBuffers and reconfigure the scanners...</p>\n"}, {'answer_id': 8397129, 'author': 'Nikolaus Very Permana', 'author_id': 961567, 'author_profile': 'https://Stackoverflow.com/users/961567', 'pm_score': 3, 'selected': False, 'text': '<p>This is my example solution to avoid WSAcancelblablabla:\nDefine your thread as global then you can use invoke method like this:</p>\n\n<pre><code>private void closinginvoker(string dummy)\n    {\n        if (InvokeRequired)\n        {\n            this.Invoke(new Action&lt;string&gt;(closinginvoker), new object[] { dummy });\n            return;\n        }\n        t_listen.Abort();\n        client_flag = true;\n        c_idle.Close();\n        listener1.Stop();\n    }\n</code></pre>\n\n<p>After you invoke it, close the thread first then the forever loop flag so it block further waiting (if you have it), then close tcpclient then stop the listener.</p>\n'}, {'answer_id': 51034620, 'author': 'SimonNZ', 'author_id': 7186618, 'author_profile': 'https://Stackoverflow.com/users/7186618', 'pm_score': 0, 'selected': False, 'text': '<p>More recently I saw this exception when using HttpWebRequest to PUT a large file and the Timeout period was passed.</p>\n\n<p>Using the following code as long as your upload time > 3 seconds it will cause this error as far as I could see.</p>\n\n<pre><code>string path = "Reasonably large file.dat";\nint bufferSize = 1024;\nbyte[] buffer = new byte[bufferSize];\nSystem.Net.HttpWebRequest req = (HttpWebRequest)System.Net.HttpWebRequest.Create("Some URL");\nreq.Method = "PUT";\nreq.Timeout = 3000; //3 seconds, small timeout to demonstrate\nlong length = new System.IO.FileInfo(path).Length;\nusing (FileStream input = File.OpenRead(path))\n{\n    using (Stream output = req.GetRequestStream())\n    {\n        long remaining = length;\n        int bytesRead = 0;\n        while ((bytesRead = input.Read(buffer, 0, (int)Math.Min(remaining, (decimal)bufferSize))) &gt; 0)\n        {\n            output.Write(buffer, 0, bytesRead);\n            remaining -= bytesRead;\n        }\n        output.Close();\n    }\ninput.Close();\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/31871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3263/']