Reputation: 13620
In MainPage.xaml.cs I have created a BackgroundWorker. This is my code:
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();
}
But this does not work. How can i properly stop the backgroundworker when navigating to another page?
Upvotes: 0
Views: 178
Reputation: 36113
Create a signal such as ManualResetEvent
.
ManualResetEvent _evStop = new ManualResetEvent(false);
Instead of doing Thread.Sleep()
, wait on your event object for your desired "delay" time.
_evStop.WaitOne(1000*60*5, false);
When you want to stop processing early, raise the signal on your event object.
_evStop.Set();
When the event is signalled, your WaitOne will return early. Otherwise, it will time out after your specified amount of time.
Upvotes: 1