如何使用WP7计划任务处理异步网络I / O?

时间:2011-08-14 17:59:17

标签: windows-phone-7

使用Mango,可以创建计划任务来更新ShellTiles数据。

完成任务后,可以调用NotifyComplete()

鉴于手机上的I / O应该是异步的,在调用NotifyComplete()之前如何确保I / O完整?

通过同步灵感来源?或者,一旦任务通知手机的操作系统完成后,是否允许I / O完成?

同步灵长类动物是明显的答案,但在手机上,阻挡并不是一个好的选择。

1 个答案:

答案 0 :(得分:3)

计划任务不会同步执行。它们被启动,然后有15秒时间来强制终止NotifyComplete(或中止)。

直接回答您的问题,您将使用异步IO方法,然后从完整事件或回调中调用NotifyComplete

这是一个例子。我已经使用了Microsoft.Phone.Reactive内容,但如果您愿意,可以使用传统方式使用Begin / EndGetResponse。

public class SampleTask : ScheduledTaskAgent
{
    protected override void OnInvoke(ScheduledTask task)
    {
        HttpWebRequest request = WebRequest.CreateHttp("http://stackoverflow.com");

        Observable.FromAsyncPattern<WebResponse>(
                request.BeginEndResponse,
                request.EndGetResponse
            )()
            .Subscribe(response =>
            {
                // Process the response
                NotifyComplete();

            }, ex =>
            {
                // Process the error
                Abort(); // Unschedules the task (if the exception indicates 
                         // the task cannot run successfully again)
            });

        // Synchronous control flow will continue and exit the OnInvoke method
    }
}
相关问题