Windows Phone asynchronous call terminates

91 views Asked by At

I am creating a Rest Communication interface for a small windows phone application since you can not call SOAP web services. The interface is simple and uses JsonConverter to parse json responses.

Code looks like this

    public class Communicate<RequestType,ResposeType> where ResposeType:class  where RequestType :class
{

     public async Task< ResposeType> CommunicateSvr(RequestType _parameter,string methodName,string serverIp)
     {
         String reqData = JsonConvert.SerializeObject(_parameter);

         HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, serverIp+methodName);
         request.Content = new StringContent(reqData, Encoding.UTF8, "application/json");

         HttpClient client = new HttpClient();
         client.DefaultRequestHeaders
             .Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);



         if (response.StatusCode == HttpStatusCode.OK)
             return JsonConvert.DeserializeObject<ResposeType>(await response.Content.ReadAsStringAsync());
         else
             throw new Exception("Error connecting to " + serverIp+methodName+ " ! Status: " + response.StatusCode);

     }
}

I am facing a big problem. When the code reach to

HttpResponseMessage response = await 
client.SendAsync(request,HttpCompletionOption.ResponseHeadersRead);            

the thread ends , terminates and the application seems to stop. Is still running but is not doing anything. I set two breakpoints one after the other and the second was never reached. I don't what's wrong, I have searched the web a lot but I did not found anything useful. Thanks in advance, waiting for your response

On the output windows I got the following message:

The thread 0xdec has exited with code 259 (0x103).
The thread 0x2180 has exited with code 259 (0x103).
1

There are 1 answers

0
Stephen Cleary On BEST ANSWER

You're probably calling Task.Wait or Task<T>.Result further up your call stack, which will cause a deadlock that I explain on my blog. In this case, your UI thread will deadlock (not exit).

The best fix is to change Wait or Result to await.