
我不用这个定时器的时候所有的功能都正常,但是只要开了这个定时器UI界面就会卡死,按理来说timer不是另起线程嘛,还是我这个写的有问题

引用chatGPT作答,由于定时器是在另一个线程上执行的,而 Dispatcher.BeginInvoke 将操作分发到主线程上执行,因此在定时器的回调函数中使用 Dispatcher.BeginInvoke 可能会导致主线程的阻塞。这可能会导致卡顿或 UI 界面失去响应。
此外,使用定时器时,应该避免进行过多的操作,以免对应用程序的性能产生负面影响。如果需要执行较长时间的操作,可以考虑使用后台线程或异步方法。
建议你使用 DispatcherTimer,它是专门为 WPF 应用程序设计的,它可以在 UI 线程上运行,从而避免可能出现的阻塞问题。同时,DispatcherTimer 也比 System.Timers.Timer 更容易使用。
下面是一个使用 DispatcherTimer 的示例代码:
private DispatcherTimer waitTimer;
public void Wait(int index)
{
path.Style = canvas.Resources["red"] as Style;
GlobalSub temp = FindSub(this.subwayID);
temp.strState = "临时停车";
this.listIndex = index;
waitTimer = new DispatcherTimer();
waitTimer.Interval = TimeSpan.FromSeconds(1 / GlobalData.doubleSpeed);
waitTimer.Tick += WaitTime;
waitTimer.Start();
}
private void WaitTime(object sender, EventArgs e)
{
double X1, X2, Y1, Y2;
X1 = this.ellipse1.Center.X;
Y1 = this.ellipse1.Center.Y;
X2 = TrackModel.listSubway[listIndex - 1].ellipse1.Center.X;
Y2 = TrackModel.listSubway[listIndex - 1].ellipse1.Center.Y;
Console.WriteLine(TrackModel.listSubway[listIndex - 1].subwayID);
if (Scheduling.IsResum(X1, Y1, X2, Y2) == 1)
{
Console.WriteLine("c# IF");
Resum();
path.Style = canvas.Resources["green"] as Style;
waitTimer.Stop();
}
}
这个例子使用 DispatcherTimer 替换了 System.Timers.Timer,并且不再需要使用 Dispatcher.BeginInvoke。