我想每隔几秒加载一张图片.我创建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];
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我现在空了.
void timer_Tick(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)
一种选择是使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能希望确保button_click在异步循环仍在迭代时不会重新进入.检查Lucian Wishick的"Async re-entrancy,以及处理它的模式".
如果你坚持使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |