我创建了一个包含线程的程序。有一个带有面板的按钮,当面板被线程访问时,按钮应自动将其背景颜色变为粉红色。再次按下按钮时,它应该变成绿色。我的问题是当线程访问该面板时,按钮不会变成粉红色,而是保持默认颜色。但是当我点击它改变颜色。
这是我所做的:-
//这是按钮点击事件
public void btn_Click(object sender, System.EventArgs e)
{
locked = !locked; //makes the locked variable true if it is false and vice versa
this.btn.BackColor = locked ? Color.Pink : Color.Green;
lock (this)
{
if (!locked)
{
Monitor.Pulse(this);
}
}
}
这是执行时的代码,按钮应自动变为粉红色。
public void start2()
{
Thread.Sleep(delay);
while (true)
{
semaphore.Signal();
this.ZeroPlane();
panel.Invalidate();
buff.read(ref colour, ref status);
for (int k = 0; k < 5; k++)
{
panel.Invalidate();
this.movePlane(xDelta, yDelta);
Thread.Sleep(delay);
locked = true;
}
if (status == "1" || status =="2" || status == "3") //checks whether it has arrived at the destination
{
lock (this)
{
while (locked)
{
Monitor.Wait(this); //keep the plane in the hub until the button is pressed.
}
}
semaphore.Wait();
buff.write(this.colour, this.status); //overwrites the buffer
buff.read(ref colour, ref status);
for (int p = 0; p < 5; p++)
{
this.westEast = true;
this.movePlane(0, 20);
Thread.Sleep(delay);
panel.Invalidate();
}
nextSemaphore.Wait();
nextBuffer.write(this.colour, "0");
this.colour = Color.Yellow;
this.status = null;
}
}