调度程序计时器滴答函数未在另一个线程中调用 [英] Dispatcher timer tick function not called in anther thread

查看:42
本文介绍了调度程序计时器滴答函数未在另一个线程中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共部分类 MainWindow : Window{公共主窗口(){初始化组件();线程 HeartRateThread = new Thread(startThread);HeartRateThread.Name = "Class1";HeartRateThread.Start();}私有无效开始线程(对象对象){新的 Class1();}}公开课 Class1{公共类 1(){DispatcherTimer timer1 = new DispatcherTimer();timer1.Interval = new TimeSpan(0,0,0,1);timer1.Tick += timer1_tick;timer1.Start();}private void timer1_tick(对象发送者,EventArgs e){Debug.WriteLine("定时器调用");}}

我试图从另一个线程启用这个 timer_tick 函数,因为它在 maInWindow 的代码部分很明显.但是,调用了 Class1 构造函数但未启用 timertick functin.但是,如果我在主线程上执行此操作,则一切正常.任何原因.我怎样才能让它工作?

解决方案

DispatcherTimer 只能在 UI 线程上运行.但是,在您的情况下,您正在后台线程上创建 DispatcherTimer.DispatcherTimer,在内部尝试获取 Dispatcher.CurrentDispatcher,在您的情况下,它为后台线程而不是主 UI 线程获取调度程序.

你真的需要DispatcherTimer吗?如果您不打算在 timer1_tick 方法中操作任何 UI 元素,那么最好使用不同的计时器,例如 System.Timers.Timer.>

请参阅以了解有关可用的更多信息.net 中的计时器.

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Thread HeartRateThread = new Thread(startThread);
        HeartRateThread.Name = "Class1";
        HeartRateThread.Start();
    }

    private void startThread(object obj)
    {
        new Class1();
    }
}

 public class Class1
{
    public  Class1()
    {
        DispatcherTimer timer1 = new DispatcherTimer();
        timer1.Interval = new TimeSpan(0,0,0,1);
        timer1.Tick += timer1_tick;
        timer1.Start();
    }

    private void timer1_tick(object sender, EventArgs e)
    {
        Debug.WriteLine("timer called");
    }
}

I am trying to enable this timer_tick function fromanother thread as it is obvious in the code section of maInWindow. However, the Class1 constructor is called but timertick functin is not enabled. However if i do this on the main thread, everything works fine. Any reason for this.And how can I get it working?

解决方案

DispatcherTimer can only work run on a UI thread. However, in your case you are creating a DispatcherTimer on a background thread. DispatcherTimer, internally tries to get Dispatcher.CurrentDispatcher, in your case it gets dispatcher for the background thread, not for the main UI thread.

Do you really need DispatcherTimer? If you are not going to manipulate any UI elements in the timer1_tick method, then you are better off to go with a different timer, like System.Timers.Timer.

Refer to this to read more about available Timers in .net.

这篇关于调度程序计时器滴答函数未在另一个线程中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆