WPF UI 在 while 循环期间一直冻结 [英] WPF UI keeps freezing during while loop
本文介绍了WPF UI 在 while 循环期间一直冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此代码期间,我的 UI 冻结并且不会像我希望的那样更新,尽管控制台写入行工作正常,所以我确定它完全按照我想要的方式进行循环
During this code my UI freezes and doesn't update like i would like although the console write line works perfectly so im sure it is going through the loop exactly how i want
while (true)
{
MyMethod();
}
void MyMethod() {
Console.WriteLine(DateTime.Now);
TimeSpan duration = SetDate - DateTime.Now;
int days = duration.Days + 1;
string strDays = days.ToString();
string LeftorAgo = "";
if (strDays[0] == '-')
{
LeftorAgo = "ago";
}
else
{
LeftorAgo = "left";
}
this.Dispatcher.Invoke(() =>
{
ShowDate.Text = $"{strDays.TrimStart('-')}\n days {LeftorAgo}";
ShowSubject.Text = Subject;
});
System.Threading.Thread.Sleep(5000);
}
在 Darkonekt 的帮助下进行编辑我使用他的计时器技术解决了这个问题,并且效果很好,谢谢!代码如下
Edit with Darkonekt's help i solved this issue using his timer technique and it works perfectly thank you! code below
private System.Windows.Threading.DispatcherTimer remainTimer = new System.Windows.Threading.DispatcherTimer();
InitializeComponent();
remainTimer.Tick += new EventHandler(MyMethod);
remainTimer.Interval = TimeSpan.FromSeconds(5);
remainTimer.Start();
void MyMethod(object sender, EventArgs e) {
...
感谢您的帮助
推荐答案
使用 DispatcherTimer 而不是 while 循环:
Use a DispatcherTimer instead of while loop:
private DispatcherTimer remainTimer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
remainTimer.Tick += MyMethod;
remainTimer.Interval = TimeSpan.FromSeconds(5);
remainTimer.Start();
}
private void MyMethod(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now);
TimeSpan duration = SetDate - DateTime.Now;
int days = duration.Days + 1;
string strDays = days.ToString();
string LeftorAgo = "";
if (strDays[0] == '-')
{
LeftorAgo = "ago";
}
else
{
LeftorAgo = "left";
}
ShowDate.Text = $"{strDays.TrimStart('-')}\n days {LeftorAgo}";
ShowSubject.Text = Subject;
}
这篇关于WPF UI 在 while 循环期间一直冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文