4

The objective is to keep a Boolean variable in High state for 2 seconds after a button is pressed.

The Variable should be in high state when Mouse_Down event is fired. Also the variable should be high for the next 2 seconds also, after the MouseUp event is fired. So basically I want to create a delay between these two events.

Is there any way to do this?

bool variable;

private void button1_MouseDown(object sender, EventArgs e)
{
   variable = true; // This variable should be true for 2 seconds after mouseUp event is fired.
}

private void button1_MouseUp(object sender, EventArgs e)
{
   variable = False;
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
impulse101
  • 99
  • 1
  • 10
  • 1
    You should use timer to change the variable value after 2 seconds. . start the timer in button down. Set the interval value to 2 seconds for timer .. and change the value in tick event of timer – Chetan Dec 18 '19 at 07:16
  • You can also try sleeping the Thread for 2 secs by putting `Thread.Sleep(2000)`; in the mouse up event Handler – Ndubuisi Jr Dec 18 '19 at 07:23
  • You can change your accepted answer. – Theraot Dec 18 '19 at 07:42
  • @Theraot `Sleep` is so much easier... There is no way of race conflicts like you have with timers... (and all just for small price of totally frozen UI :) ). Now I agree that `Sleep` is bad suggestion in this case, but it's OP's call to decide what works for them... or maybe just trolling future visitors with bad suggestion :) And top voted answer for similar question https://stackoverflow.com/questions/5449956/how-to-add-a-delay-for-a-2-or-3-seconds unconditionally suggests `Sleep` (trolling all the way) – Alexei Levenkov Dec 18 '19 at 07:50
  • 1
    @AlexeiLevenkov Just telling OP it is possible, in case OP is unaware. – Theraot Dec 18 '19 at 07:56
  • @AlexeiLevenkov nice edit in the other post, but now we have a working duplicate that even encompases the async approach. So shall we close this one? – Mong Zhu Dec 18 '19 at 09:10
  • @Theraot Op probably cannot use async, because it might be homework, and if you present such a concept like async/await, the professor/tutor will notice quite fast that this solution is not developed by yourself. ;) – Mong Zhu Dec 18 '19 at 09:12

1 Answers1

9

You could make the event async and use Task.Delay(2000) to wait 2 seconds (2000 milliseconds) and then put the boolean into false state:

using System.Threading.Tasks;

private async void button1_MouseUp(object sender, EventArgs e)
{
   await Task.Delay(2000);
   variable = False;
}

This would ensure that the GUI remains responsive and will introduce literally a delay.

Here is some complementary reading to the concept of async await might be worth spending the time some day ;)

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76