我正在使用DispatcherTimer调用方法在不同的线程中执行。我正在运行一个简单的程序,不需要真正担心效率低下。如何让UI线程等待DispatcherTimer完成,同时仍然允许DispatcherTimer线程对UI进行更改?
*我理解这可能是半重复的,但我看到的例子都是特定于案例的。感谢
private void spinButton_Click(object sender, RoutedEventArgs e)
{
minSelTextBlock.Text = "";
Index = 0;
maxIndex = rnd.Next(40, 60);
DispatcherTimer timer;
timer = new DispatcherTimer(DispatcherPriority.Normal);
timer.Interval = TimeSpan.FromMilliseconds(60);
timer.Tick += new EventHandler(TimerTick);
timer.Start();
selPeople[x].IsCheck = false;
displayCount++;
Index = 0;
maxIndex = rnd.Next(40, 60);
timer = new DispatcherTimer(DispatcherPriority.Normal);
timer.Interval = TimeSpan.FromMilliseconds(60);
timer.Tick += new EventHandler(TimerTick);
timer.Start();
selPeople[x].IsCheck = false;
displayCount++;
displayImage2b.Source = new BitmapImage(new Uri(selPeople[0].ImgPath));
}
private void TimerTick(object sender, EventArgs e)
{
minSelTextBlock.Text = "";
x = rnd.Next(0, selPeople.Count);
while (x == temp)
{
x = rnd.Next(0, selPeople.Count);
}
if (displayCount == 0)
displayImage1a.Source = new BitmapImage(new Uri(selPeople[x].ImgPath));
if (displayCount == 1)
displayImage2a.Source = new BitmapImage(new Uri(selPeople[x].ImgPath));
if (++Index >= maxIndex)
{
((DispatcherTimer)sender).Stop();
}
Index++;
temp = x;
}
基本上我需要TimerTick来获取selPeople [x]之前的最终x值.IsCheck = false,因为重点是删除刚刚从列表中选择的项目。
答案 0 :(得分:0)
如果希望调用方法等待调用方法的结果,可以使用.Net 4.5中提供的Async / Await
您可以这样做:
private async void spin()
{
minSelTextBlock.Text = "";
Index = 0;
maxIndex = rnd.Next(40, 60);
DispatcherTimer timer;
timer = new DispatcherTimer(DispatcherPriority.Normal);
timer.Interval = TimeSpan.FromMilliseconds(60);
timer.Tick += new EventHandler(StartTicker);
timer.Start();
selPeople[x].IsCheck = false;
displayCount++;
Index = 0;
maxIndex = rnd.Next(40, 60);
await Ticker();
selPeople[x].IsCheck = false;
displayCount++;
displayImage2b.Source = new BitmapImage(new Uri(selPeople[0].ImgPath));
}
Private Task<void> StartTicker()
{
Task.Run<void>(()=>Ticker());
}
private void Ticker()
{
while(your condition is true)
{
minSelTextBlock.Text = "";
x = rnd.Next(0, selPeople.Count);
while (x == temp)
{
x = rnd.Next(0, selPeople.Count);
}
if (displayCount == 0)
displayImage1a.Source = new BitmapImage(new Uri(selPeople[x].ImgPath));
if (displayCount == 1)
displayImage2a.Source = new BitmapImage(new Uri(selPeople[x].ImgPath));
if (++Index >= maxIndex)
{
break;
}
Index++;
temp = x;
Thread.Sleep(60);
}
}
我没有使用计时器,而是使用了While Loop
和Thread.Sleep()
,它与您的计时器相同。
如果你想了解async / await我真的推荐this
再见,我没有编译这段代码。所以它可能有一些语法或其他错误。