C# 如何每5分钟检查一次,并在需要时中断检查?

C# 如何每5分钟检查一次,并在需要时中断检查?,c#,multithreading,windows-phone-7,C#,Multithreading,Windows Phone 7,在MainPage.xaml.cs中,我创建了一个BackgroundWorker。这是我的代码: protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); bgw = new BackgroundWorker(); bgw.WorkerSupportsCancellation

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

但这是行不通的。导航到另一页时,如何正确停止backgroundworker?

创建一个信号,如
ManualResetEvent

ManualResetEvent _evStop = new ManualResetEvent(false);
不要执行
Thread.Sleep()
,而是在事件对象上等待所需的“延迟”时间

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

_evStop.Set();

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

这听起来可能有点傻,但为什么不改用计时器呢?猜测windows phone的正确计时器是Dispatchermer。
_evStop.Set();