Dispatchertimer tick函数未在另一个线程中调用

时间:2013-10-28 09:01:46

标签: wpf multithreading

 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");
    }
}

我正在尝试启用这个timer_tick函数,因为它在maInWindow的代码部分很明显。但是,调用了Class1构造函数,但未启用timertick功能。但是,如果我在主线程上执行此操作,一切正常。这有什么原因。我怎样才能让它发挥作用?

4 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

也许你可以尝试这样的事情:

private void timer1_tick(object sender, EventArgs e)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() => Debug.WriteLine("timer called")));
}

答案 2 :(得分:0)

未经测试,我猜你必须在构建时将MainWindow的Dispatcher传递给DispatcherTimer。否则它将创建自己的:

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

...

public Class1(Dispatcher dispatcher)
{
    DispatcherTimer timer1 =
        new DispatcherTimer(DispatcherPriority.Background, dispatcher);

    timer1.Interval = new TimeSpan(0,0,0,1);
    timer1.Tick += timer1_tick;
    timer1.Start();
}

答案 3 :(得分:0)

您可以使用Dispatcher来调用startThread方法。

 object objParameter = "parametervalue";
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(
                                                                                () => startThread(objParameter)));