RSS リーダーを構築しています。新しいフィード アイテムをチェックする定期的なタスクを追加したいと考えています。新しいアイテムが見つかった場合は、それに応じてアプリのライブ タイルが更新されます。
私が遭遇した問題は、DownloadStringAsync() メソッドを使用してフィードをダウンロードし、フィードに新しいアイテムが含まれているかどうかを確認していることです。そのため、ダウンロード プロセスに 20 秒 (アクションを完了するために定期的なタスクが与えられる時間) よりも長くかかる場合があります。
私が望むのは、20 秒のアクションの後、エージェントが OS によって終了される前に NotifyComplete() メソッドが確実に呼び出されるようにすることだけです。このため、ティック イベントで NotifyComplete() メソッドを呼び出す、15 秒間隔のディスパッチャー タイマーを登録したいと考えています。
しかし、ディスパッチャ タイマーを宣言して使用しようとすると、無効なクロススレッド アクセス エラーが発生しました。私の定期的なタスク コードには、次のものが含まれます。
public class ScheduledAgent : ScheduledTaskAgent
{
//Register a DispatcherTimer
DispatcherTimer masterTimer = new DispatcherTimer();
private static volatile bool _classInitialized;
public ScheduledAgent()
{
if (!_classInitialized)
{
_classInitialized = true;
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
});
}
//Set Timer properties
masterTimer.Interval = TimeSpan.FromSeconds(15);
masterTimer.Tick += masterTimer_Tick;
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
masterTimer.Start();
//Call DownloadStringAsync() and perform other tasks...
//Call NotifyComplete() after the download is complete.
//
}
private void masterTimer_Tick(object sender, EventArgs e)
{
masterTimer.Stop();
//There is no more time left, we must call NotifyComplete() so as to avoid
//having the periodic task terminated by the OS
NotifyComplete();
}
}
問題は、なぜこれが起こっているのか、どうすれば問題を解決できるのかということです。前もって感謝します!