嗨! 我使用wpf开发了一个非常小的应用程序.我使用了一个名称/id为myCanvas的画布.然后,我在此画布上放置了一个按钮和文本框控件.我希望当我按下按钮时,我的文本框将显示从1到10的数字,持续时间为一秒.意思是,文本框显示1然后等待1秒,然后显示2,然后再次等待1秒,然后显示3,然后再次等待1秒,以此类推,直到10(..这是一个计数器.我的代码如下:
Hi! I have developed a very small application using wpf. I used a canvas with name/id myCanvas. Then i placed a button and textbox controls on this canvas. I wanted that when i clik on button then my textbox display numbers from 1 to 10 with one second duration. Means, textbox diplay 1 then wait for 1 second then display 2 and again wait for 1sec then 3 and again wait for 1second and so on till 10 (..it is a counter. My code for this is as:
namespace numberGenDelayThread { public partial class MainWindow : Window { int n = 1; public MainWindow() { InitializeComponent(); } private void btn_Start_Click(object sender, RoutedEventArgs e) { while (n < =10) { txt_Number.Text = n.ToString(); delay(1000); n++; } } void delay(double ms) { DateTime dt = DateTime.Now.AddMilliseconds(ms); while (DateTime.Now <= dt) { ; } } } }问题:该程序等待近9秒钟,然后在文本框中仅显示10(在代码中名称为txt_Number). 它没有显示1秒持续时间从1到10的数字...换句话说,它没有像计数器那样扭曲.为什么会这样? 我该如何解决? 我应该使用帆布还是其他容器?
Problem: This program waits for almost 9 seconds and then display only 10 in textbox (with name txt_Number in code). It did not display numbers from 1 to 10 with 1second duration...in other words it did not wrok like counter. Why this so? how can i solve this? should i use canvas or some other container? how can i achieve this in wpf?
推荐答案当然当然,它会等待所有迭代并仅显示最后一个值.您如何想象它还能以其他方式工作?您使UI线程处于休眠状态,因此它无法更新视图. 令人惊讶的是您提到线程"一词,而实际上没有使用线程.您正在UI线程中调用Thread.Sleep,但绝对不要这样做.您也不应在UI线程中进行任何阻塞调用或仅花费任何明显时间的调用.您需要在单独的线程中执行此操作.除了… 您无法从非UI线程调用与UI相关的任何操作.相反,您需要使用System.Windows.Threading.Dispatcher的Invoke或BeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms). 在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例: Control.Invoke()与Control.BeginInvoke() [ ^ ], Treeview扫描仪和MD5的问题 [ ^ ]. 另请参阅有关线程的更多参考资料: 如何获取keydown事件在vb中的不同线程上操作 [ ^ ], 启用禁用+多线程后控件事件不会触发 [ ^ ].
更多推荐
在wpf中做一个计数器
发布评论