【问题标题】:HttpClient with PostAsync code optimisation具有 PostAsync 代码优化的 HttpClient
【发布时间】:2017-01-19 04:34:08
【问题描述】:

我正在使用下面的代码,代码运行良好。我是 HTTPClient 的新手,所以我不确定这段代码是否得到了适当的优化,或者什么是最好的编码方式。我发现这个例子讨论了死锁,尽管它是关于并行编程的,但我只是想确保这段代码是否可以针对性能或错误进行改进/优化。

我使用某些关键参数连接到网站并返回 json 数据。我会处理以采取进一步行动。

protected void btnClient_Click(object sender, EventArgs e)
    {
        using (var client = new HttpClient())
        {

            client.BaseAddress = new Uri("https://secure.telr.com/");
            client.DefaultRequestHeaders.ExpectContinue = false;
            var result = client.PostAsync("gateway/order.json",
                new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ivp_method", "create"),
                new KeyValuePair<string, string>("ivp_store", "12345"),
                new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
                new KeyValuePair<string, string>("ivp_cart", "123452"),
                new KeyValuePair<string, string>("ivp_desc", "Descripion"),
                new KeyValuePair<string, string>("ivp_test", "1"),
                new KeyValuePair<string, string>("ivp_amount", "10.00"),
                new KeyValuePair<string, string>("ivp_currency", "UAD"),
                new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("ivp_framed", "1"),
            })).Result;


            var jsonData = (JObject)JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            dynamic jObj = JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            string url = jsonData["order"]["url"].ToString();
            Response.Write("<br>url" + url + "<br>");

            ltrTelr.Text = "<iframe id= 'telr' src='" + url + "' ></iframe>";

        }
    }

【问题讨论】:

    标签: c# asp.net optimization dotnet-httpclient


    【解决方案1】:

    当您不确定您的 API 是否/何时返回数据时,您应该避免尝试访问 Task.Result。这会阻止您的线程,因为它正在尝试评估结果。

    相反,当您调用异步方法时,您应该使用 'await' 关键字来释放线程,如下所示:

    protected async Task btnClient_Click(object sender, EventArgs e)
    {
        using (var client = new HttpClient())
        {
    
            client.BaseAddress = new Uri("https://secure.telr.com/");
            client.DefaultRequestHeaders.ExpectContinue = false;
            var result = await client.PostAsync("gateway/order.json",
                new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ivp_method", "create"),
                new KeyValuePair<string, string>("ivp_store", "12345"),
                new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
                new KeyValuePair<string, string>("ivp_cart", "123452"),
                new KeyValuePair<string, string>("ivp_desc", "Descripion"),
                new KeyValuePair<string, string>("ivp_test", "1"),
                new KeyValuePair<string, string>("ivp_amount", "10.00"),
                new KeyValuePair<string, string>("ivp_currency", "UAD"),
                new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("ivp_framed", "1"),
            }));
    
            var rawData = await result.Content.ReadAsStringAsync();
    
            var jsonData = (JObject)JsonConvert.DeserializeObject(rawData);
            dynamic jObj = JsonConvert.DeserializeObject(rawData);
    
            string url = jsonData["order"]["url"].ToString();
            Response.Write("<br>url" + url + "<br>");
    
            ltrTelr.Text = "<iframe id= 'telr' src='" + url + "' ></iframe>";
    
        }
    }
    

    【讨论】:

    • 我收到以下错误 ` 'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法,并将其返回类型更改为 'Task'。`
    • Task.WaitAll(Task.Run(async () =&gt; { .... await result.Content.ReadAsStringAsync(); }
    • 哦,对不起,是的,当您使用 await 时,您也必须使您的方法异步。返回类型“任务”是 void (msdn.microsoft.com/en-us/magazine/jj991977.aspx) 的异步等效项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多