我有一个循环,在该循环中我正在运行一个Dispatcher Timer。这是我的代码:
Dim dt As New DispatcherTimer
dt.Interval = TimeSpan.FromSeconds(5)
AddHandler dt.Tick, AddressOf ChangeLabel
Dim items as new List(Of String) From {"Apple","Orange","Banana"}
For Each i In List
Me.Title = i
dt.StartTimer()
System.Threading.Thread.Sleep(5000)
Next
Private Sub ChangeLabel
'Show dt elapsed time in a label
End Sub
基本上我想要的是在每次打开5秒后显示项目列表中的每个项目暂停。我想在标签中显示已用时间,经过时间后,按5秒显示下一个项目。使用Thred.Sleep方法无法实现这一点,因为它只会将我的应用程序冻结5秒钟,并显示下一个项目,而不会使用已用时间更新标签。
那么使用什么而不是Thread.Sleep来冻结应用程序并用经过的时间更新标签?
答案 0 :(得分:1)
我从BackgroundWorker
开始。这是让你入门的东西(在C#中)。
(VB中的代码应该非常相似。)
worker = new BackgroundWorker();
worker.DoWork += (sender, doWorkEventArgs) =>
{// stuff to do during every iteration of background worker (long-running process)
#region DoWork
foreach(string label in labels)
{
worker.ReportProgress(0, label);
Thread.Sleep(5000);// 5-sec sleep on bg thread
}
#endregion DoWork
};
worker.ProgressChanged += (sender, e) =>
{
#region DoWork Progress (executed on UI thread, so invoke not required)
string text = e.UserState as string;
//update control
#endregion DoWork Progress (executed on UI thread, so invoke not required)
};
worker.RunWorkerAsync(null);// start background worker