2012-04-26 78 views
1

说明:更新Windows窗体 - C#

结构:Windows窗体 - 三个组件:文本框,文本框响应和按钮。

问题:我正在用C#windows窗体移动电机:我正在启动电机,并在中间以10秒的延迟时间单向按钮单击电机的运动方向
。即我启动电机,有10秒延迟,然后使电机反转。我想在开始时显示“开始”,在10秒延迟结束时显示“结束”。我曾尝试使用线程,但它不起作用。但我只能在文本框中看到“完成”而不是“开始”。代码如下:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 

namespace SampleThreadProgram 
{ 
    public partial class Form1 : Form 
    { 
      static EventWaitHandle _waitHandle = new AutoResetEvent(false); 
      delegate void SetTextCallback(string text); 

    void SetText(string text) 
    { 
      if (textBox.InvokeRequired) 
      { 
      SetTextCallback d = new SetTextCallback(SetText); 
      BeginInvoke(d, new object[] { text }); 
      } 
      else 
      { 
      textBox.Text = text; 
      } 
    } 

    void UpdateTextBox(string message) 
    { 
     SetText(message); 
     _waitHandle.Set(); 
    } 

    void Wait() 
    { 
     for (ulong i = 0; i < 10000; i++) 
     { 
      for (ulong j = 0; j < 100000; j++) 
      { 
      } 
     } 

    } 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     UpdateTextBox("Start"); 
     _waitHandle.WaitOne(); 
     Thread.Sleep(10000); 
     UpdateTextBox("Finish"); 

    } 

    } 
} 

回答

0

没有足够的时间让UI更新。在SetText(message);UpdateTextBox之后添加Application.DoEvents();

+0

Servy的答案更多地解决了代码问题,而不仅仅是回答提出的问题,就像我的答案一样。 – zimdanen 2012-04-26 18:33:45

4
  1. 您不应该使用大的长for循环使计算机等待一段时间。至少使用Thread.Sleep
  2. 你应该使用BackgroundWorker来做你想做的事情。在按钮单击事件中设置开始文本,然后启动后台工作程序。您可以让事件DoWork做一些工作(在这种情况下为睡眠)并使用WorkerCompleted事件来更新UI。

使用后台工作器的好处是您不必担心更新非UI线程的代码形式。在按钮单击事件中,您可以直接更新文本框的文本,并且BackGroundWorker线程已经确保Completed事件在UI线程中运行,所以即使在那里您也可以直接访问UI控件。 BGW专门设计用于使这个确切的案例更容易。