WSACancelBlockingCall exception

后端 未结 5 1052
生来不讨喜
生来不讨喜 2020-12-24 00:51

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

System.Net.Sockets.SocketException: A blocking operation was interrupt         


        
5条回答
  •  情话喂你
    2020-12-24 01:25

    More recently I saw this exception when using HttpWebRequest to PUT a large file and the Timeout period was passed.

    Using the following code as long as your upload time > 3 seconds it will cause this error as far as I could see.

    string path = "Reasonably large file.dat";
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    System.Net.HttpWebRequest req = (HttpWebRequest)System.Net.HttpWebRequest.Create("Some URL");
    req.Method = "PUT";
    req.Timeout = 3000; //3 seconds, small timeout to demonstrate
    long length = new System.IO.FileInfo(path).Length;
    using (FileStream input = File.OpenRead(path))
    {
        using (Stream output = req.GetRequestStream())
        {
            long remaining = length;
            int bytesRead = 0;
            while ((bytesRead = input.Read(buffer, 0, (int)Math.Min(remaining, (decimal)bufferSize))) > 0)
            {
                output.Write(buffer, 0, bytesRead);
                remaining -= bytesRead;
            }
            output.Close();
        }
    input.Close();
    }
    

提交回复
热议问题