本文介绍了HttpWebRequest 随机失败并异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做几个 POST 请求.

I would like to do serveral POST-Request.

我的问题是应用程序在 Task 中随机崩溃.do_POST()-在我的 async void bt_publishPath_Click()-Event 中的 await 期间的函数.

My problem is that the Application crashes randomly in the Task<...> do_POST()-Function during await in my async void bt_publishPath_Click()-Event.

我可以执行一些 POST 请求(一切正常),有时 await 会阻塞,应用程序崩溃并显示 System.NullReferenceException(经过很长时间的等待).我不明白为什么会这样,因为它第一次起作用.

I can do some POST-Requests (everything's working fine) and sometime the await will block and the app crashes with a System.NullReferenceException (after a long time of waiting). I don't understand why this is happing because the first times it is working.

这是我目前得到的:

我已经注释掉了所有不重要的功能.我已经在没有这些代码行的情况下测试了我的代码,并且也发生了错误.

// MainWindow
private async void bt_publishPath_Click(object sender, RoutedEventArgs e)
{
    // gr_spinner.Visibility = Visibility.Visible;

    ApiResponse res = await ApiCall.do_POST(
        "/path",
        getBasicAuthString(),
        flink.getJsonString()
    );

    // gr_spinner.Visibility = Visibility.Collapsed;
    // Globals.errorHandling(res.Statuscode, res.Parameters[0]);
}

// ApiCall static Class
public static Task<ApiResponse> do_POST(string apiPath, string auth, string json)
{
    return Task.Run(() =>
    {
        int statuscode = 0;
        HttpWebResponse response = null;
        try
        {
            // HEADER
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiBase + apiPath);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Add("Authorization", auth);

            // DATA
            byte[] data = Encoding.ASCII.GetBytes(json);
            request.ContentLength = data.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            // SEND AND GET RESPONSE
            /*
             * It seems to be that GetResponse() isn't called correctly.
             * The Backend doesn't receive a POST-request and the reponse stays null.
             */
            response = (HttpWebResponse)request.GetResponse();
            statuscode = (int)response.StatusCode;
        }
        catch (WebException ex)
        {
            statuscode = (int)((HttpWebResponse)ex.Response).StatusCode;
        }
        return new ApiResponse(statuscode, null, new String[] { apiPath });
    });
}

附加信息:

在使用 async 和 await 执行此操作之前,我尝试使用 BackgroundWorker 解决此问题.在这种情况下,我遇到了类似的问题:有时上一次 POST 的 backgroundWorker 仍然很忙,程序无法启动新的(死锁).

Before doing this with async and await I tried to solve this issue by using a BackgroundWorker. In this case I had a similar problem: Sometimes the backgroundWorker of the previous POST was still busy and the program wasn't able to start a new one (deadlock).

此外我发现了一些有趣的事情:async await 任务空引用异常

Furthermore I have found something interesting: async await Task null reference exception

  • 但在这种情况下,它是一个 ASP.NET 应用程序.我正在开发 Windows 桌面客户端 - 而不是服务器应用程序.所以这并没有真正的帮助.

感谢您的帮助!

推荐答案

在你的 catch 块中有 (HttpWebResponse)ex.Response.

In your catch block you have (HttpWebResponse)ex.Response.

来自 MSDN:

如果可以从 Internet 资源获得响应,则包含来自 Internet 资源的错误响应的 WebResponse 实例;否则为空.

所以你的问题是一个无响应的服务器和你的错误处理错误.
但是不要解决这个问题,查找 HttpClient 并编写一个新的 async Task<>DoPost(...).

So your problem is a non-responsive server and an error in your error handling.
But don't fix this, look up the HttpClient and write a new async Task<> DoPost(...).

这篇关于HttpWebRequest 随机失败并异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:59
查看更多