第二次尝试后,HttpWebRequest.GetRequestStream()停止(异步)c#

时间:2017-11-09 17:26:17

标签: c# unity3d stream httpwebrequest

我的环境版本是2.0,我目前正在使用Unity 5.5,c#。 我第三次尝试获取HttpWebRequest请求流时遇到了停顿。

我想要实现的是拥有"重试"的机制:当我发送请求时,我等待响应,如果超时,我发送另一个请求并刷新超时。当我点击MAX_ATTEMPTS或其中一个请求得到响应时(即使它来自已超时的请求),我会停止此循环。

处理此循环的代码在这里:

mean = mean_vec

TIMEOUT是TimeSpan的10秒。 IsAnyResultCompleted只是一个for循环,用于检查是否有任何请求将IsCompleted设置为true。

在这里,我创建并发送请求:

    IEnumerator DoRequest()
    {
        List<IAsyncResult> results = new List<IAsyncResult>(MAX_ATTEMPTS);
        int attemptNumber = 1;
        while (attemptNumber <= MAX_ATTEMPTS)
        {
            IAsyncResult result = null;
            try
            {
                result = SendRequest();
            }
            catch (Exception e)
            {
                ProcessException(e);
                yield break;
            }

            if (result != null)
            {
                results.Add(result);
                DateTime timeOutTime = DateTime.UtcNow + TIMEOUT;
                yield return null;
                while (DateTime.UtcNow < timeOutTime)
                {
                    int completedIndex = -1;
                    if (IsAnyResultCompleted(results, out completedIndex) == true)
                    {
                        ProcessResponse(results[completedIndex]);
                        yield break;
                    }
                    else
                    {
                        yield return null;
                    }
                }

            }
            attemptNumber++;
        }

        if (results.Count != 0)
        {
            ProcessResponseFail("Timed out");
        }
        else
        {
            ProcessResponseFail("Unable to generate a request");
        }
    }

&#34; onResponse&#34;是一个缓存的委托,它被分配给:

    IAsyncResult SendRequest()
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestActionPath);

        request.ContentType = "application/json";
        request.Accept = "application/json";
        request.Method = "POST";

        string json = JsonUtility.ToJson(_dependency);

        using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
        {
            sw.Write(json);
            sw.Flush();
        }

        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(onResponse), request);

        return result;
    }

我很清楚this并且我也尝试设置ServicePointManager.DefaultConnectionLimit = 1000000但是结果总是相同的,在SendRequest的2个发送请求GetRequestStream()之后停顿了5秒钟我无法理解为什么

0 个答案:

没有答案