0

我对wp7开发并不陌生,目前正在开发一个应用程序,该应用程序具有后台代理以根据从Web调用到api的响应更新值。如何在后台代理中进行同步Web呼叫

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

有没有什么办法可以在后台代理中进行同步调用,以便我可以在同一个代理中处理结果?

我已经尝试处理共享库中类中的Web调用,但异步调用仅在代理的onInvoke方法完成后才会生成,因此无用。任何想法都会很棒。

回答

1

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

0

你可以使用像这样的的AutoResetEvent:

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(); 
} 

记住,你应该检查一下连接可用并处理可能的例外,如果你的后台代理会连续被杀两次(由于内存消耗或持续时间),它将被操作系统禁用。