gpt4 book ai didi

c# - 不眠等待?

转载 作者:太空狗 更新时间:2023-10-30 00:18:45 25 4
gpt4 key购买 nike

我想做的是启动一个函数,然后将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com