簡體   English   中英

如何重構異步方法以使其同步?

[英]How to refactor the async method to make it synchronous?

我需要同步運行以下異步代碼:

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;
    }

首先,我想指出以下答案: 如何同步運行異步Task <T>方法?

由於不鼓勵僅鏈接的答案,因此您可以嘗試以下方法:

  • Task.Synchronously運行
  • Task.Wait-通常被認為是有害/危險的,因為混合Task.Wait和async / await可能會導致死鎖。
  • 只需在需要結果的地方使用“等待”即可。 這並不是真正地(顯然)同步運行,但在大多數情況下是可行的。 很少有充分的理由嘗試運行異步
  • 從另一個答案: BlahAsync().GetAwaiter().GetResult()

使您的FetchAsync異步,然后就可以等待它。 代碼如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM