在 MainPage.xaml.cs 我创建了一个 BackgroundWorker。这是我的代码:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
bgw = new BackgroundWorker();
bgw.WorkerSupportsCancellation = true;
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.RunWorkerAsync();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
bgw.CancelAsync();
base.OnNavigatedFrom(e);
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
return;
}
Thread.Sleep(1000*60*5); // 5 minutes
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled || (sender as BackgroundWorker).CancellationPending)
return;
/* the work thats needed to be done with the ui thread */
(sender as BackgroundWorker).RunWorkerAsync();
}
但这不起作用。导航到另一个页面时如何正确停止后台工作程序?