0

I am fairly new to wp7 development, and currently developing an app that has a background agent to update values based upon responses it gets from a web call to an api.

My problem is that the response to the web call is an asynchronous call and I can not access the results returned from within the background agent.

Is there any way that i can make a synchronous call from within the background agent so as to allow me to deal with the results within the same agent?

I have tried dealing with the web call within a class in a shared library but the Asynchronous call is only made after the onInvoke method of the agent has finished and so no use. Any Ideas would be great.

user1865044
  • 301
  • 3
  • 9

2 Answers2

1

You simply need to call the NotifyComplete() method in your async call's Completed handler, and not before. Remove the call at the end of Invoke.

Jeremy Gilbert
  • 361
  • 3
  • 9
0

you could use an AutoResetEvent like this:

protected override void OnInvoke(ScheduledTask task)
{
  AutoResetEvent are = new AutoResetEvent(false);

  //your asynchronous call, for example:
  WebClient wc = new WebClient();
  wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
  wc.OpenReadAsync(searchUri, channel);

  // lock the thread until web call is completed
  are.WaitOne();

  //finally call the NotifyComplete method to end the background agent
  NotifyComplete(); 
}

and your callback method should look like:

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  //do stuff with the web call response

  //signals locked thread that can now proceed
  are.Set();
}

remember that you should check if a connection is available and handle possible exceptions, if your background agent gets killed twice consecutively (due to memory consumed or duration) it will be disabled by the OS.