gpt4 book ai didi

c# - DispatcherTimer 等待循环

转载 作者:行者123 更新时间:2023-12-01 15:02:03 24 4
gpt4 key购买 nike

我想每隔几秒加载一张图片。我创建了 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)
{

}

最佳答案

一种选择是使用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();
}
}

关于c# - DispatcherTimer 等待循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24075350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com