C# WPF UI在while循环期间保持冻结状态
在这段代码中,我的UI冻结了,没有像我所希望的那样更新,尽管控制台写行工作得很好,所以我确信它正按照我所希望的方式通过循环C# WPF UI在while循环期间保持冻结状态,c#,wpf,while-loop,textblock,C#,Wpf,While Loop,Textblock,在这段代码中,我的UI冻结了,没有像我所希望的那样更新,尽管控制台写行工作得很好,所以我确信它正按照我所希望的方式通过循环 while (true) { MyMethod(); } void MyMethod() { Console.WriteLine(DateTime.Now); TimeSpan duration =
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的帮助下编辑我用他的定时器技术解决了这个问题,效果非常好谢谢!
代码如下
private System.Windows.Threading.DispatcherTimer remainTimer = new System.Windows.Threading.DispatcherTimer();
感谢您的帮助使用Dispatcher而不是while循环:
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;
}
使用Dispatcher而不是while循环:
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;
}
虽然(true)永远不会跳出循环,这意味着您的ui永远是糟糕的,但我认为问题在于“System.Threading.Thread.Sleep(5000);”这一行您正在使主线程休眠,请在线程中调用它。将您的工作放在异步方法中或使用单独的线程来执行您的工作。使用dispatcherI更新UI有一个问题,这段代码在哪里执行?在click事件处理程序中?或者在哪里?如果你真的想每5秒做一些代码,那么在循环中使用wait Task.Delay(5000)或某种计时器。如果希望代码在ui线程上运行,则使用Dispatchertimer。while(true)将永远不会退出循环,这意味着您的ui将永远无法运行。我认为问题在于“System.Threading.thread.Sleep(5000);”这一行您正在使主线程休眠,请在线程中调用它。将您的工作放在异步方法中或使用单独的线程来执行您的工作。使用dispatcherI更新UI有一个问题,这段代码在哪里执行?在click事件处理程序中?或者在哪里?如果你真的想每5秒做一些代码,那么在循环中使用wait Task.Delay(5000)或某种计时器。如果希望代码在ui线程上运行,请使用Dispatchermer。