Click here to Skip to main content
15,890,185 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am working on a metro app in which I am sending a web request in background service but not getting web response. I coded like this:


private void SendRequest(string url, Action<string> OnResponse, string requestParameter)
{


HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "text/xml";


request.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = request.EndGetRequestStream(req);

using (StreamWriter w = new StreamWriter(outStream))
w.Write(requestParameter);

request.BeginGetResponse(delegate(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string response1 = reader.ReadToEnd();
OnResponse(response1);
}
}
}
catch (Exception ex)
{
}
}, null);
}, null);

}

I also tried like this

HttpClient client = new HttpClient();
HttpContent content = new StringContent(requestParameter);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
HttpResponseMessage response = await client.PostAsync(url, content);

Is there any reason why I am not getting response or any other method to do this. I executed the same code in normal execution and works perfect but not in background service.
Posted

1 solution

Hi ,

It was just two lines to add and its working now. Create an instance of BackgroundTaskDeferral class at start point of background service and call its complete method where you think that this was the last task.

private BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

_deferral.Complete();

Actually what was happening is async calls are not invoking. Background service is just executing code and does not wait for async calls. So by using deferral it notifies service that there are some async calls also and complete method notifies that everything gonna complete.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900