So I have a button that lately will be capable of open a door through SerialPort
. To do that I will send something to it and wait for a response from it which is already configured and developed.
But I am getting some trouble to set a Thread.Sleep()
.
This is what I got inside of the button:
private void cmdOpenDoor_Click(object sender, EventArgs e)
{
Thread.Sleep(5000);
Task.Factory.StartNew(this.Demo);
}
And the Demo
method is:
private void Demo()
{
string questionMark= "?";
string incoming = comport.ReadExisting();
string carriageReturn = "\r";
comport.Write(questionMark+ "(" + carriageReturn);
Cursor.Current = Cursors.WaitCursor;
if (txtTest.Text == "@q")
{
MessageBox.Show("Door opened!", MessageBoxButtons.OK, MessageBoxIcon.Information);
pbGreen.Show();
pbRed.Hide();
}
else
{
MessageBox.Show("The door is already opened!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
When I will open the door it shows the "Door opened" message and when it tries to execute the pbGreen.Show()
the applications stops and an error comes:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
Do you have any idea how can I solve it? I cannot Invoke a PictureBox