如何杀死在UserControl视图模型上启动的计时器

时间:2013-12-12 16:00:25

标签: c# wpf timer viewmodel

在UserControl的视图模型构造函数中,我启动一个每30秒运行一次的计时器。 当我关闭这门课时,我需要找到一种方法来阻止它。

using System.Threading;
namespace uc
{
    class UserControlViewModel
    {
        Timer timer;

        public UserControlViewModel()
        {
            //Each five seconds check to see if the current user has had their module access permissions changed
            timer = new Timer(CheckUserModuleAccess, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
        }

        private void CheckModuleAccess(object state)
        {
            ...
        }
    }
}

2 个答案:

答案 0 :(得分:2)

向viewmodel添加析构函数,停止并销毁计时器:

using System.Threading;
namespace uc
{
    class UserControlViewModel
    {
        Timer timer;

        ...

        // Desctructor
        ~UserControlViewModel()
        {
            // Stop the timer when the viewmodel gets destroyed
            timer.Stop();
            timer.Dispose();
            timer = null;
        }
    }
}

如果不这样做,请尝试在viewModel上实现IDisposeable

答案 1 :(得分:0)

我相信您正在寻找的解决方案是Dispose Pattern

using System;
using System.Threading;

namespace uc
{
    class UserControlViewModel : IDisposable
    {
        Timer timer;

        public UserControlViewModel()
        {
            //Each five seconds check to see if the current user has had their module access permissions changed
            timer = new Timer(CheckUserModuleAccess, null, TimeSpan.Zero, TimeSpan.FromSeconds(30));
        }

        private void CheckModuleAccess(object state)
        {
            ...
        }

        public void Close()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing){
                if (timer != null) {
                    timer.Stop();
                    timer.Dispose();
                    timer = null;
                }
            }
        }

        ~UserControlViewModel()
        {
            Dispose(false);
        }

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            Close();
        }

        #endregion
    }
}