积极答复者
DipatcherTimer与Timer的比较疑问?

问题
-
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Thread t = new Thread(new ThreadStart(Test)); t.IsBackground = true; t.Start(); } void Test() { DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Interval = new TimeSpan(0, 0, 2); dispatcherTimer.Tick += timer_Tick; dispatcherTimer.Start(); System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 1000; timer.Elapsed += aTimer_Elapsed; timer.Start(); } void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Console.WriteLine("Timer"); } void timer_Tick(object sender, EventArgs e) { Console.WriteLine("DispatcherTimer"); } }
新建WPF工程,然后写了如上的代码:
我的疑问是在线程中我写了DispatherTimer计时器与Timer计时器
然后开启;可是在DispatherTimer计时器里的方法我打断点在:
Console.WriteLine("DispatherTimer");上却根本不执行
难道是dispatherTimer计时器未开启成功吗?
相比较Timer却可以成功执行;请运行比较下;
然后解释下我的疑问,谢谢了!!!
- 已移动 Bob Shen 2012年10月23日 3:38 (发件人:Visual C#)
答案
-
因为你的DispatcherTimer是建立在新的Thread上的,所以该DispatcherTimer没有Dispatcher,永远不会响应,你可以显式地指定Dispatcher来使该DispatcherTimer工作。
DispatcherTimer dt = new DispatcherTimer(DispatcherPriority.Normal, this.Dispatcher);
这是一个关于Dispatcher的链接:http://msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatcher%28v=vs.110%29.aspx
Wanpeng wanpeng.ones@gmail.com
- 已编辑 Wanpeng 2012年10月23日 7:18
- 已标记为答案 JackSlaterYu 2012年10月23日 7:50
全部回复
-
-
因为你的DispatcherTimer是建立在新的Thread上的,所以该DispatcherTimer没有Dispatcher,永远不会响应,你可以显式地指定Dispatcher来使该DispatcherTimer工作。
DispatcherTimer dt = new DispatcherTimer(DispatcherPriority.Normal, this.Dispatcher);
这是一个关于Dispatcher的链接:http://msdn.microsoft.com/zh-cn/library/system.windows.threading.dispatcher%28v=vs.110%29.aspx
Wanpeng wanpeng.ones@gmail.com
- 已编辑 Wanpeng 2012年10月23日 7:18
- 已标记为答案 JackSlaterYu 2012年10月23日 7:50