0

I need to run the following async code synchronously:

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

The full code looks:

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;
    }
S. Koshelnyk
  • 478
  • 1
  • 5
  • 20
  • Possible duplicate of [How would I run an async Task method synchronously?](http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously) – EJoshuaS - Stand with Ukraine Dec 06 '16 at 23:26
  • a) Why do you want to do that? b) Have you looked at [this answer](http://stackoverflow.com/questions/5095183/how-would-i-run-an-async-taskt-method-synchronously)? – EJoshuaS - Stand with Ukraine Dec 06 '16 at 23:29
  • @EJoshuaS, I want to call another activity when the async method finishes. But the problem is that the compiler ignores starting the activity. I looked at it but this code is different to my. – S. Koshelnyk Dec 06 '16 at 23:58

2 Answers2

0

First, I would like to point out the following answer: How would I run an async Task<T> method synchronously?

Since link-only answers are discouraged, here are a few things mentioned there that you could try:

  • Task.RunSynchronously
  • Task.Wait - this is often considered harmful/dangerous because mixing Task.Wait and async/await can result in deadlocks.
  • Just use "await" where you need the result. This isn't really running it synchronously (obviously) but in most cases that works. There are rarely good reasons to try to run an asynchronous
  • From the other answer: BlahAsync().GetAwaiter().GetResult()
Community
  • 1
  • 1
0

Make your FetchAsync to be async then you can await on it. The code as below:

using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(uri);
                    string tx = await response.Content.ReadAsStringAsync();                        
                }
Yuri S
  • 5,355
  • 1
  • 15
  • 23
  • I also see the problem. You call StartActivity(new Intent(this, typeof(MainActivity))); inside FetchAsync unconditionally in the middle of the function. What do you expect to happen? – Yuri S Dec 07 '16 at 23:18