1

まず、この投稿をお読みいただきありがとうございます。

SQL データベースから 60 秒ごとに「製品」をダウンロードするタイマー クラスがあります。つまり、他のユーザーによって編集された可能性のある更新された製品を確認するためです。

ここに私のクラスコードがあります:

public class GetProducts : INotifyPropertyChanged
    {
        public GetProducts()
        {
            Timer updateProducts = new Timer();
            updateProducts.Interval = 60000; // 60 second updates
            updateProducts.Elapsed += timer_Elapsed;
            updateProducts.Start();
        }

        public ObservableCollection<Products> EnabledProducts
        {
            get
            {
                return ProductsDB.GetEnabledProducts();
            }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("EnabledProducts"));
        }

        public event PropertyChangedEventHandler PropertyChanged;

    }

次に、これを XAML (WPF) コントロールのタグ プロパティにバインドします。

<Page.Resources>
    <!-- Products Timer -->
    <products_timer:GetProducts x:Key="getProducts_timer" />
</Page.Resources>


Tag="{Binding Source={StaticResource getProducts_timer}, Path=EnabledProducts, Mode=OneWay}"

これは本当にうまくいきます。私が抱えている問題は、コントロールがホストされているウィンドウまたはページが閉じると、タイマーが何があっても刻々と進み続けることです。

ページ/コントロールが利用できなくなったら、ティッカーを停止する方法を提案できますか?

お時間をいただきありがとうございました。すべてのヘルプは大歓迎です。

4

1 に答える 1

6

まず、タイマーへの参照を保持することから始めます。

private Timer updateProducts;
public GetProducts()
{
    updateProducts = new Timer();
    ......
}

StopUpdatesたとえば、呼び出されるとタイマーを停止する別のメソッドを作成します。

public void StopUpdates()
{
     updateProducts.Stop();
}

ウィンドウの OnUnloaded イベントでタイマーを停止します。

private void MyPage_OnUnloaded(object sender, RoutedEventArgs e)
{
    var timer = this.Resources["getProducts_timer"] as GetProducts;
    if (timer != null)
        timer.StopUpdates();
}
于 2012-12-19T12:02:57.320 に答える