以下代码有两个线程,每个线程将 20 写入string str
其相应的文本框。完成后,Thread t00
发出Thread t01
启动信号并将共享string str
从y更改为x。Thread t00
应将 20 y写入文本框,并将Thread t01
20 x写入另一个文本框。相反,Thread t00
最终写 19 y和 1 x。但是,如果我Thread.Sleep()
在设置 EventWaitHandle 之前添加一个,则可以解决我遇到的问题(我得到 20 x和 20 y),但是为什么呢?EventWaitHandle
不应该只在循环完成后设置,有或没有Thread.Sleep()
.
public partial class MainWindow : Window
{
public string str = "y";
static EventWaitHandle _waitHandle = new AutoResetEvent(false);
public MainWindow()
{
InitializeComponent();
Thread t00 = new Thread(() =>
{
for (int i = 0; i < 20; i++)
{
Thread.Sleep(200);
Action action00 = () =>
{
tb00.AppendText(str);
};
Dispatcher.BeginInvoke(action00);
}
Thread.Sleep(200); // <-- why this fix the problem??
_waitHandle.Set();
});
t00.Start();
Thread t01 = new Thread(() =>
{
Action action00 = () =>
{
tb01.AppendText("Waiting...\n");
};
Dispatcher.BeginInvoke(action00);
_waitHandle.WaitOne();
str = "x";
for (int i = 0; i < 20; i++)
{
Thread.Sleep(200);
Action action = () =>
{
tb01.AppendText(str);
};
Dispatcher.BeginInvoke(action);
}
});
t01.Start();
}
}