puradox
puradox

Reputation: 1468

Easiest way to delay

What is the easiest/simplest way to delay inside a function without having to delay the main thread?
This is what I am trying to do is similar to this:

    private void FallingToggle(bool a)
    {
        a = true;
        Thread.Sleep(1000);
        a = false;
    }

But I found that it froze the whole program.
Is there a way around this? Or is there a more simple way to approach this?

Upvotes: 1

Views: 268

Answers (2)

user153498
user153498

Reputation:

Responding to your comment, there are many ways what you're trying to do can be achieved.

One way is to record the time when the action occurs the first time (this can be achieved using DateTime.Now). Then, if any subsequent actions occur within one second of the recorded time, return immediately. Example:

DateTime lastActionTime = DateTime.Now;

// ...

if ((DateTime.Now - lastActionTime).Milliseconds < 1000)
{
    // Too soon to execute the action again
    return;
}

// Do whatever the action does...

Another way to do this, in the case that you want to disable a button for one second, is to use a Timer (there are several timers in the .NET Framework, I'm using the Winforms version here). Once the action occurs, you disable the button or other UI element, and then start a Timer, with an interval of one second. Once the timer goes off, you can reenable the UI element, allowing the user to execute the action again. Example:

// In a constructor or something
timer = new System.Windows.Forms.Timer();
timer.Interval = 1000; // 1000 milliseconds
timer.Tick += (s, e) => 
{
    button.Enabled = true;
    timer.Stop();
};

// ...

void OnButtonClick()
{
    button.Enable = false;
    timer.Start();

    // Do whatever the button does...
}

The latter is what you would use in a GUI, the former could be used in something like a game.

Upvotes: 6

9T9
9T9

Reputation: 698

Here's the way..

In the function call event after a = true; start a new thread. And put

Thread.Sleep(1000);
    a = false;  

in the new thread.

I think this is the easiest way.

Upvotes: 0

Related Questions