2016-12-06 55 views
0

我需要同步運行下面的異步代碼:如何重構異步方法使其同步?

using (var httpClient = new System.Net.Http.HttpClient()) 
     { 
      var stream = GetStreamAsync(url); 
      StreamReader reader = new StreamReader(url); 
      jsonString = reader.ReadToEnd(); 
     } 

完整的代碼如下:

protected override void OnCreate(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 

     SetContentView(Resource.Layout.anim_layout); 

     Animation myAnimation = AnimationUtils.LoadAnimation(this, Resource.Animation.MyAnimation); 
     ImageView myImage = FindViewById<ImageView>(Resource.Id.imageView1); 

     myImage.StartAnimation(myAnimation); 

     FindViewById<Button>(Resource.Id.button1).Click+=delegate 
     { 
      StartActivity(new Intent(this, typeof(MainActivity))); 
     }; 
    } 

    public string dataByCity(string city) 
    { 
     var url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&APPID=" + AppID; 

     //ТОРМОЗИТ ЗДЕСЬ/BRAKES HERE 
     FetchAsync(url); 
     return city; 
    } 

    public double Data_down(double lat, double lon) 
    { 

     var url = String.Format(
      "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=metric&APPID=" + AppID); 

     //ТОРМОЗИТ ЗДЕСЬ/BRAKES HERE 
     FetchAsync(url); 

     return lat; 
    } 

    private void FetchAsync(string url) 
    { 
     string jsonString; 

     using (var httpClient = new System.Net.Http.HttpClient()) 
     { 
      var stream = GetStreamAsync(url); 
      StreamReader reader = new StreamReader(url); 
      jsonString = reader.ReadToEnd(); 
     } 

     var json = jsonString; 

     StartActivity(new Intent(this, typeof(MainActivity))); 

     JsonValue firstitem = json; 
     var mydata = JObject.Parse(json); 

     cityTextGlobal = (mydata["name"]).ToString(); 

     string GovnoData = (mydata["main"]).ToString(); 

     //spliting string 
     string[] values = GovnoData.Split(','); 
     for (int i = 0; i < values.Length; i++) 
     { 
      values[i] = values[i].Trim(); 
      if (i == 0) 
      { 
       //tempGlobal = values[i]; 
       GovnoTemperature = values[i]; 
      } 
     } 
     tempGlobal = null; 
     foreach (char c in GovnoTemperature) 
     { 
      if (c == '.') 
      { 
       break; 
      } 
      if (c == '-' || char.IsDigit(c) == true || c == '.') 
      { 
       tempGlobal += c.ToString(); 
      } 
     } 
     // startAct(); 

     //return jsonString; 
    } 
+0

的可能的複製[?我將如何運行的異步任務方法同步(http://stackoverflow.com/questions/5095183/how-would-i-run-an- async-taskt-method-synchronous) – EJoshuaS

+0

a)你爲什麼要這麼做? b)你看過[這個答案](http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously)? – EJoshuaS

+0

@EJoshuaS,我想在異步方法結束時調用另一個活動。但問題是編譯器忽略啓動活動。我看着它,但這段代碼與我的不同。 –

回答

0

首先,我想指出以下幾點回答:How would I run an async Task<T> method synchronously?

由於鏈接 - 只回答不鼓勵,這裏有幾件事你可以嘗試:

  • Task.RunSynchronously
  • Task.Wait - 這通常是considered harmful/dangerous,因爲混合Task.Wait和async/await可能導致死鎖。
  • 只需在需要結果的地方使用「等待」。這並不是真正的同步運行(很明顯),但在大多數情況下都可以運行。很少有很好的理由來嘗試運行異步
  • 從對方的回答:BlahAsync().GetAwaiter().GetResult()
0

讓您FetchAsync是異步,那麼你可以在上面等候。如下面的代碼:

using (var httpClient = new HttpClient()) 
       { 
        var response = await httpClient.GetAsync(uri); 
        string tx = await response.Content.ReadAsStringAsync();       
       } 
+0

我也看到了這個問題。你可以調用StartActivity(new Intent(this,typeof(MainActivity)));在函數中間無條件地在FetchAsync中。你期望發生什麼? –