Neuxz
Neuxz

Reputation: 336

Endless wait for async Web Response

i have the following problem, i try to wait for for an Async Web Response. But it never finished.

  public string getTermine(string trmId)
    {
        System.Threading.Tasks.Task<string> lisi = LoadTermine((HttpWebRequest)WebRequest.Create("http://" + curent.usrCH + apiKey + curent.phrase + apiTrmIDIS + trmId));//Request get String result like http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start="+i+"&q=
        lisi.Wait();
        return lisi.Result;
    }
    private async System.Threading.Tasks.Taskstring>LoadTermine(HttpWebRequest myRequest)
    {
        //List<Termine> terminListe = new List<Termine>();
        List<Appointment> Resu = null;
        using (WebResponse response = await myRequest.GetResponseAsync())
        {
            using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
            {
                Resu = reader.ReadToEnd();

            }
        }
        return Resu;
    }

P.S. I cant use and synchronous request because this methods are an part of the Base code which is used by iOS, WinPhone and Android and i dont know why i cant get an synchronous WebResponse.

Upvotes: 0

Views: 397

Answers (1)

wishmaster
wishmaster

Reputation: 1303

You are creating a deadlock by calling .Result on the task.

You could do something like this where the remoteUrl variabled is the url of your web service

private async System.Threading.Tasks.Task<string> LoadTermineAsync(HttpWebRequest myRequest)
{
    using (var client = new HttpClient()) {
        using (var request = new HttpRequestMessage(HttpMethod.Get, myRemoteUrl)) {
            var response = await client.SendAsync(request).ConfigureAwait(false);

            var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return result;
        }
    }
}

For more info on Async/Await

And this evolve video is a little bit more advanced.

Upvotes: 3

Related Questions