【问题标题】:WebApi Task An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was fullWebApi 任务 由于系统缺少足够的缓冲区空间或队列已满,无法对套接字执行操作
【发布时间】:2014-12-12 20:25:55
【问题描述】:

我正在使用 asp.net webapi 当我向返回任务的 Webapi 端点发出 http 请求时,我偶尔会收到此错误

在此响应中,我使用 await 来确保线程在所有线程完成其任务之前不会关闭。

基本上我有一个 Post 方法:

 public async Task<HttpResponseMessage> PostHouse(SessionModal sessionModal)
 {
 // create database context
 // Create a new house object
 House h = new House();
 h.address= await GetFormattedAddress(sessionModal.location)

  //save database
 }
public async Task<FormattedAdress> GetFormattedAddress(DBGeography Location)
{
 var client = new HttpClient();
 // create URI 
var URI = new URi......
Stream respSream= await client.GetStreamAsync(URI) 
// Data Contract Serializer
// Create Formatted Address
FormatedAddress address =....
return address; 
 }

代码工作了一段时间,但随着时间的推移,我开始得到错误响应:

“无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满”

如果我重新启动服务器,问题会暂时得到缓解。如果我一直收到此错误,但是我尝试 POST、GET、Delete 或 PUT 不同的控制器端点,它将起作用。但如果我返回并尝试发布端点 PostHouse,我仍然会收到错误消息。

是否有可能线程没有被释放,正在使用的端口永远不会被释放?

编辑

这是我正在尝试修复的确切代码。我尝试使用 using(){} 但是我仍然收到错误消息。我认为有些东西忘记处理了。我几乎是从帖子中获取图像,而不是将其发送到 Blob 存储。如果有更好的方法可以做到这一点,我也不介意这些建议。

    public async Task<HttpResponseMessage> Post()
    {
        var result = new HttpResponseMessage(HttpStatusCode.OK);
        if (Request.Content.IsMimeMultipartContent())
        { try{
           await Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
            {

                MultipartMemoryStreamProvider provider = task.Result;
                foreach (HttpContent content in provider.Contents)
                {
                    using (Stream stream = content.ReadAsStreamAsync().Result) { 
                    Image image = Image.FromStream(stream);
                    var testName = content.Headers.ContentDisposition.Name;
                    String[] header = (String[])Request.Headers.GetValues("userId");
                    int userId = Int32.Parse(header[0]);
                    using (var db = new studytree_dbEntities())
                    {
                        Person user = db.People.Find(userId);


                        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
         ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

                        //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                        //  CloudConfigurationManager.GetSetting("StorageConnectionString"));
                        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                        // Retrieve a reference to a container. 
                        CloudBlobContainer container = blobClient.GetContainerReference("profilepic");

                        // Create the container if it doesn't already exist.
                        container.CreateIfNotExists();
                        container.SetPermissions(new BlobContainerPermissions
                        {
                            PublicAccess =
                                BlobContainerPublicAccessType.Blob
                        });

                        string uniqueBlobName = string.Format("image_{0}.png",
               header[0]);

                        CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
                        user.ProfilePhotoUri = blob.Uri.ToString();
                        user.Student.ProfilePhotoUri = blob.Uri.ToString();
                        user.Tutor.ProfilePhotoUri = blob.Uri.ToString();
                        using (var streamOut = new System.IO.MemoryStream())
                        {
                            image.Save(streamOut, ImageFormat.Png);
                            streamOut.Position = 0;

                            blob.UploadFromStream(streamOut);
                            db.SaveChanges();
                        }
                    }
                    }


                }

            });
                 }
                catch (Exception e)
                {

                 JObject m=   JObject.Parse(JsonConvert.SerializeObject(new {e.Message,e.InnerException}));
                    return Request.CreateResponse<JObject>(HttpStatusCode.InternalServerError,m);
                }

            return Request.CreateResponse(HttpStatusCode.OK);



        }

        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));





        }

    }

【问题讨论】:

  • 旁注 - 您可以改用 ReadAsAsync&lt;T&gt;。将节省您手动反序列化和处置流的需要

标签: c# sockets asp.net-web-api task


【解决方案1】:

你没有处理你的Stream

试试这个

public async Task<FormattedAdress> GetFormattedAddress(DBGeography Location)
{
    using(var client = new HttpClient())
    {
        var URI = new URi......
        using(Stream respSream= await client.GetStreamAsync(URI))
        {
            FormatedAddress address =....
            return address; 
        }
    }
}

发生的情况是您的网络流处于打开状态,而您的计算机可以建立的连接数量有限。通过不处理它们,您可以抓住它们。所以未来的请求不能使用这些连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多