0

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

但这不起作用。导航到另一个页面时如何正确停止后台工作程序?

4

1 回答 1

1

创建一个信号,例如ManualResetEvent

ManualResetEvent _evStop = new ManualResetEvent(false);

不要这样做Thread.Sleep(),而是等待您的事件对象等待您想要的“延迟”时间。

_evStop.WaitOne(1000*60*5, false);

如果您想提前停止处理,请在事件对象上发出信号。

_evStop.Set();

当事件发出信号时,您的 WaitOne 将提前返回。否则,它将在您指定的时间后超时。

于 2013-05-23T18:27:31.363 回答