説明:
構造: Windows フォーム - 3 つのコンポーネント: テキスト ボックス、テキスト ボックスの応答、およびボタン。
問題: C# Windows フォームでモーターを動かしています: モーターを始動
し、途中で 10 秒遅れてボタンを 1 回クリックするだけでモーターの動きの方向を反転させます。つまり、モーターを始動し、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");
}
}
}