Search code examples
c#functionwait

Waiting without Sleeping?


What I'm trying to do is start a function, then change a bool to false, wait a second and turn it to true again. However I'd like to do it without the function having to wait, how do I do this?

I can only use Visual C# 2010 Express.

This is the problematic code. I am trying receive user input (right arrow for example) and move accordingly, but not allow further input while the character is moving.

        x = Test.Location.X;
        y = Test.Location.Y;
        if (direction == "right") 
        {
            for (int i = 0; i < 32; i++)
            {
                x++;
                Test.Location = new Point(x, y);
                Thread.Sleep(31);
            }
        }
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int xmax = Screen.PrimaryScreen.Bounds.Width - 32;
        int ymax = Screen.PrimaryScreen.Bounds.Height - 32;
        if (e.KeyCode == Keys.Right && x < xmax) direction = "right";
        else if (e.KeyCode == Keys.Left && x > 0) direction = "left";
        else if (e.KeyCode == Keys.Up && y > 0) direction = "up";
        else if (e.KeyCode == Keys.Down && y < ymax) direction = "down";

        if (moveAllowed)
        {
            moveAllowed = false;
            Movement();
        }
        moveAllowed = true;  
    }

Solution

  • Use Task.Delay:

    Task.Delay(1000).ContinueWith((t) => Console.WriteLine("I'm done"));
    

    or

    await Task.Delay(1000);
    Console.WriteLine("I'm done");
    

    For the older frameworks you can use the following:

    var timer = new System.Timers.Timer(1000);
    timer.Elapsed += delegate { Console.WriteLine("I'm done"); };
    timer.AutoReset = false;
    timer.Start();
    

    Example according to the description in the question:

    class SimpleClass
    {
        public bool Flag { get; set; }
    
        public void function()
        {
            Flag = false;
            var timer = new System.Timers.Timer(1000);
            timer.Elapsed += (src, args) => { Flag = true; Console.WriteLine("I'm done"); };
            timer.AutoReset = false;
            timer.Start();
        }
    }