我想每隔几秒钟加载一张图片。我创建DispatcherTimer,我想在计时器滴答无所事事,只是等待间隔。我怎么能这样做?
if (window.DialogResult == true) {
st=window.st;
for(int i=0;i<=st;i++){
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,5);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
arr[i]=window.arr[i];
image1.Source = arr[i];
}
}
在这里,我现在空了。
void timer_Tick(object sender, EventArgs e)
{
}
答案 0 :(得分:6)
一种选择是使用async
/ await
:
async void button_click(object sender, RoutedEventArgs e)
{
// prepare the array
// ...
for (var i = 0; i < 100; i++)
{
image1.Source = arr[i];
await Task.Delay(5000);
}
}
您可能希望确保在异步循环仍在迭代时不会重新进入button_click
。查看Lucian Wishick的"Async re-entrancy, and the patterns to deal with it".
如果您坚持使用DispatcherTimer
:
async void button_click(object sender, RoutedEventArgs e)
{
// prepare the array
// ...
var tcs = new TaskCompletionSource<object>();
var timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,5);
timer.Tick += (_, __) => tcs.SetResult(Type.Missing);
timer.Start();
try
{
for (var i = 0; i < 100; i++)
{
image1.Source = arr[i];
await tcs.Task;
tcs = new TaskCompletionSource<object>();
}
}
finally
{
timer.Stop();
}
}