Windows phone 7 如何在后台代理中进行同步web调用

Windows phone 7 如何在后台代理中进行同步web调用,windows-phone-7,asynchronous,webclient,background-agents,Windows Phone 7,Asynchronous,Webclient,Background Agents,我是wp7开发的新手,目前正在开发一个应用程序,该应用程序有一个后台代理,可以根据它从对api的web调用中得到的响应来更新值 我的问题是,对web调用的响应是一个异步调用,我无法访问从后台代理返回的结果 是否有任何方法可以从后台代理中进行同步调用,以便允许我在同一代理中处理结果 我曾尝试在共享库中的类内处理web调用,但异步调用仅在代理的onInvoke方法完成后进行,因此没有任何用处。任何想法都很好。您只需在异步调用的已完成处理程序中调用NotifyComplete()方法,而不是在之前。在

我是wp7开发的新手,目前正在开发一个应用程序,该应用程序有一个后台代理,可以根据它从对api的web调用中得到的响应来更新值

我的问题是,对web调用的响应是一个异步调用,我无法访问从后台代理返回的结果

是否有任何方法可以从后台代理中进行同步调用,以便允许我在同一代理中处理结果


我曾尝试在共享库中的类内处理web调用,但异步调用仅在代理的onInvoke方法完成后进行,因此没有任何用处。任何想法都很好。

您只需在异步调用的已完成处理程序中调用NotifyComplete()方法,而不是在之前。在调用结束时删除调用。

您可以使用如下自动resetEvent:

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(); 
}
您的回调方法应该如下所示:

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

  //signals locked thread that can now proceed
  are.Set();
}
请记住,您应该检查连接是否可用并处理可能的异常,如果您的后台代理连续两次被杀死(由于内存消耗或持续时间),则操作系统将禁用它