I use RestSharp to execute a GET request asynchronously, but it never ends. If I make the same request Synchronously, it ends successfully. I used RestSharp the same way as before, and it always worked.
What am I doing wrong?
Here's the asynchronous method: ( this.Client is the this.Client only)
public async Task<ServiceResponse> UpvoteArticleAsync(string source, string url) { var client = this.Client; var request = new RestRequest("service/upvote/"+source+"/"+url, Method.GET) { RequestFormat = DataFormat.Json }; var cancellationTokenSource = new CancellationTokenSource(); var deserial = new JsonDeserializer(); var response = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token); return deserial.Deserialize<ServiceResponse>(response); }
and so I call it:
ServiceResponse result = await rest.UpvoteArticleAsync (this.article.Source, this.article.Url);
As I said, if I change the asynchronous synchronization method to one, it works:
public async Task<ServiceResponse> UpvoteArticleAsync(string source, string url) { var client = this.Client; var request = new RestRequest("service/upvote/"+source+"/"+url, Method.GET) { RequestFormat = DataFormat.Json }; var cancellationTokenSource = new CancellationTokenSource(); var deserial = new JsonDeserializer(); var response = client.ExecuteTaskAsync(request, cancellationTokenSource.Token); return deserial.Deserialize<ServiceResponse>(response.Result); }
EDIT:
I used try and catch to see if there are any exceptions, but he did not select.
EDIT 2:
Even if I make the same request with the HttpWebRequest from System.Net , it still gets stuck when using the asynchronous version of GetResponse :
public async Task<bool> UpvoteArticleAsync(string source, string url) { var request = HttpWebRequest.Create(string.Format(@"http://192.168.43.199:8080/service/upvote/{0}/{1}", source, url)); request.ContentType = "application/json"; request.Method = "GET"; using (HttpWebResponse response = await request.GetResponseAsync () as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var content = reader.ReadToEnd(); if(string.IsNullOrWhiteSpace(content)) { Console.Out.WriteLine("Response contained empty body..."); } else { Console.Out.WriteLine("Response Body: \r\n {0}", content); } } } return true; }