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 に答える