在WPF中睡觉循环 [英] Sleep inside for loop in wpf

查看:96
本文介绍了在WPF中睡觉循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用WPF和线程.

I have been working with WPF and threading.

我想在for循环中暂停整个屏幕(仅适用于应用程序).

I would like to pause the whole screen (the application only) during a for loop.

例如

foreach (classA a in classesA)
{
....
....
Thread.sleep(100);

}

但是,我发现它将休眠很长时间,然后一次执行所有语句. 这不是我想要的.我想在for循环的执行过程中入睡.也就是说,在第一个循环后要睡100毫秒,然后在第二个循环后要再睡.....

However, I found that it will sleep for long and then execute all the statement in a time. It is not what I want. I want to sleep within the execution of the for loop. That is to sleep 100ms after 1st loop, then sleep again after the 2nd loop.....

我发现有些文章提到了DoEvents(),但我对此并不熟悉,WPF似乎没有这种东西.

I found that some article mentioned DoEvents(), but I am not quite familiar with it and WPF seem don't have this kind of thing.

其他一些文章提到了DispatcherTimer.尽管如此,它仍不会锁定屏幕. 我想锁定整个屏幕(仅适用于应用程序),以防止在执行for循环期间单击任何按钮.

Some other articles mentioned DispatcherTimer. Still, it will not lock the screen. I would like to lock the whole screen (the application only) to prevent from clicking any button during the execution of the for loop.

我该怎么办?

非常感谢您!

推荐答案

如果您愿意尝试使用建议的asyncawait关键字,则可以使用类似的同步语义来实现睡眠行为.您需要安装异步CTP 来完成. 1

If you are willing to experiment to with the proposed async and await keywords you could achieve the sleep behavior with synchronous semantics like this. You would need to install the Async CTP to do it though.1

public aysnc void YourButton_Click(object sender, EventArgs args)
{
  foreach (classA a in classes)
  {
    await Task.Delay(100);
  }
}


1 异步CTP使用TaskEx而不是Task.


1The Async CTP uses TaskEx instead of Task.

这篇关于在WPF中睡觉循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆