c# - 不眠等待?

标签 c# function wait

我想做的是启动一个函数,然后将 bool 更改为 false,稍等片刻,然后再次将其变为 true。但是我想在函数不必等待的情况下执行此操作,我该怎么做?

我只能使用 Visual C# 2010 Express。

这是有问题的代码。我正在尝试接收用户输入(例如向右箭头)并相应地移动,但在角色移动时不允许进一步输入。

        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;  
    }

最佳答案

使用Task.Delay :

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

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

对于较旧的框架,您可以使用以下内容:

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

根据题中的描述举例:

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();
    }
}

关于c# - 不眠等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30826490/

相关文章:

c# - DataGridView 在左键单击时保持选中多行

Javascript:如何在同一页面调用函数?

java - 调用wait()时发生IllegalMonitorStateException

element - Protractor : wait for element to become invisible/hidden

c# - 带有动态下拉菜单的 MVC 3 编辑器模板

c# - EF 代码首先是 : How to delete a row from an entity's Collection while following DDD?

javascript - Json 中的解析函数

php - 为什么在 php 类中用作数组项不起作用

java - Selenium webdriver Java如何等待链接出现

c# - Parallel.ForEach 在迭代结束时表现得像每个规则一样