简体   繁体   English

WPF InitializeComponent似乎不适用于DispatcherTimer

[英]WPF InitializeComponent doesn't seem to work with DispatcherTimer

I am new to C# and also to WPF, I am trying to understand how DispatcherTimer works with GUI (WPF). 我是C#和WPF的新手,我试图了解DispatcherTimer如何与GUI(WPF)一起使用。 I want to make my application run a function every 2 seconds but still using the app itself, when I try the following code, the timer starts but I can't use the following Buttons (logout and exit), it's like the app freezes. 我想让我的应用程序每2秒运行一个函数,但仍然使用该应用程序本身,当我尝试以下代码时,计时器启动,但是我不能使用以下按钮(注销和退出),就像应用程序冻结一样。

public MainLoggedWindow()
{   
    Globals.mainLoggedWindow = this;
    InitializeComponent();


    DispatcherTimer dt = new DispatcherTimer();

    dt.Tick += new EventHandler(dtTiker);

    dt.Interval = new TimeSpan(0, 0, 1);
    dt.Start();
}

private void exit_button_Click(object sender, RoutedEventArgs e)
{
    logout_button_Click(sender, e);
    Environment.Exit(-1);
}

private void logout_button_Click(object sender, RoutedEventArgs e)
{       
    Globals.LOGGED_IN_USER.logout();
    this.Hide();
    Globals.mainWindow.Show();
}

private int increment = 0;

private void dtTiker(object sender,EventArgs e)
{       
    increment++;
    Time.Content = increment.ToString();
}

DispatcherTimer runs on the UI thread. DispatcherTimer在UI线程上运行。 It means that when the DispatcherTimer invokes its Tick method the UI thread becomes busy handling that, and it doesn't have time to handle other UI input like button clicks, so the window freezes. 这意味着,当DispatcherTimer调用其Tick方法时,UI线程变得忙于处理此操作,并且它没有时间处理其他UI输入(如按钮单击),因此窗口冻结。

What you could do is increase the interval time for your DispatcherTimer - your question desription says that it's once every two seconds, but your initialisation logic has it every one second: dt.Interval = new TimeSpan(0, 0, 1); 您可以做的是增加DispatcherTimer的间隔时间-您的问题描述说是每两秒钟一次,但是初始化逻辑每隔一秒钟就有一次: dt.Interval = new TimeSpan(0, 0, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM