Question

Making a washing machine control programme, and I want a 2 second timer in the middle of my thread. This is to represent the 'wash' time (obviously in real life its around 30 mins, but I dont want to wait that long!), then after the 2 seconds it continues with the thread. I am just working on the pause between locking the door and starting the wash, this is what I have so far :

    // Door
            if (radioButtonDoor.Checked == false)
            {
                doorOpenLight.FillColor = Color.Red;
                doorOpen.FillColor = Color.Red;
                doorUnlocked.FillColor = Color.Red;
                doorClosed.FillColor = Color.Transparent;
                doorLocked.FillColor = Color.Transparent;
                doorLight.FillColor = Color.Transparent;
            }
            else if (radioButtonDoor.Checked == true)
            {
                doorOpenLight.FillColor = Color.Transparent;
                doorOpen.FillColor = Color.Transparent;
                doorUnlocked.FillColor = Color.Transparent;
                doorClosed.FillColor = Color.Red;
                doorLocked.FillColor = Color.Red;
                doorLight.FillColor = Color.SpringGreen;
                doorLockedImage.Visible = true;
                //2 second timer here
            }
        //Wash
            if (doorLight.FillColor == Color.SpringGreen)
            {
                textBoxTemp.Text = temp.ToString();
                washLight.FillColor = Color.SpringGreen;
            }

All the colour changes are just to show my lecturer the state which the machine is in. I don't want to use sleep, as I need to be able to stop the wash at any point, so this wont be useful. Thanks

Was it helpful?

Solution

What you would do is make your method async, which will allow you to use a method called Task.Delay, which resembles Thread.Sleep, but instead of putting the thread to sleep, it returns control back to the calling method and returns after the amount of time specified has finished.

What this would require you to do is mark your method as async:

async Task FooMethod

and inside your code, you would use:

  private async void AwesomeButton_Click(object sender, EventArgs e)
  {
     doorLocked.FillColor = Color.Red;
     doorLight.FillColor = Color.SpringGreen;
     doorLockedImage.Visible = true;
     var cancellationToken = new CancellationTokenSource().Token;
     await Task.Delay(AmountOfMillisecondsHere, cancellationToken);
  }

Then, you can call cancellationToken.Cancel() to abort the Task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top