我的代码出了什么问题?它在我的localhost中运行良好,但在发布后使​​用postAsyc是错误的 [英] What's wrong with my code?It run well in my localhost,but after publish it is wrong using postAsyc

查看:172
本文介绍了我的代码出了什么问题?它在我的localhost中运行良好,但在发布后使​​用postAsyc是错误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在这里,它在我的localhost中运行良好,但在发布后它是错误的。我捕获异常,它说有一个错误叫做System.Threading.Tasks.Task.Wait Method(Int32) System.Threading.Tasks中的,CancellationToken .~1.get_Result(),如何修复代码?我的.net框架是4.0,而不是4.5。我发现带有.Result的postAsyc会导致来自网络的死锁,但如何避免呢?

My codes is here,It run well in my localhost,but after publish it is wrong .I catch the exception,It says that have a error called " System.Threading.Tasks.Task.Wait Method (Int32, CancellationToken) in System.Threading.Tasks.~1.get_Result()",How to fix the code?My .net framework is 4.0,not 4.5.I find the postAsyc with .Result can cause deathlock from the web,but how to avoid it?

try
 {
  string ip="192.165.0.6";//in fact,it is read from database
  HttpClient httpClient = new HttpClient() { BaseAddress = new Uri("http://"+ip+"/User") };
  var checkParams = new Dictionary<string, string>() {
  { "UserName","Lyly"},
  { "Password", "123456"}
  };
 var validResponse = httpClient.PostAsync("http://"+ip+"/User/CheckUserValid", new FormUrlEncodedContent(checkParams)).Result;
  if (validResponse.StatusCode == HttpStatusCode.OK && validResponse.Content.ReadAsStringAsync().Result.Contains("ValidSuccess"))
  {
    var PointData= new Dictionary<string, string>() {
   { "Math","86"},
     { "English", "90"}, 
   };

 var getResultResponse = httpClient.PostAsync("http://"+ip+"/User/SendPointData", new FormUrlEncodedContent(PointData)).Result;
  if (getResultResponse.StatusCode == HttpStatusCode.OK)
    {
      if (getResultResponse.Content.ReadAsStreamAsync().Result != null)
      {
      var reader = new StreamReader(getResultResponse.Content.ReadAsStreamAsync().Result);
      var lastResutl= JsonHelper.FromJson<LastRest>(reader.ReadToEnd());
      }
    else return "Status1";
    }
   else return "Status2";
 }
else return "Status3";
}
catch(Exception e){
return e.StackTrace;
 }

推荐答案

根据这个页面 [ ^ ] .NET 4中不支持HttpClient.PostAsync(仅4.5)。



实际上,4.0中不存在整个HttpClient 。所以我不确定你是如何在4上运行的。



编辑:



除非你正在使用此库 [ ^ ]?
According to this page[^] HttpClient.PostAsync is not supported in .NET 4 (only 4.5).

In fact, the entire HttpClient doesn't exist in 4.0. So I'm not sure how you are running it on 4.



Unless you are using this library[^]?


这篇关于我的代码出了什么问题?它在我的localhost中运行良好,但在发布后使​​用postAsyc是错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆