结构: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");
}
}
}
Servy的答案更多地解决了代码问题,而不仅仅是回答提出的问题,就像我的答案一样。 – zimdanen 2012-04-26 18:33:45