我正在尝试做的是启动一个函数,然后将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;
}
Run Code Online (Sandbox Code Playgroud)
ixS*_*Sci 10
使用Task.Delay:
Task.Delay(1000).ContinueWith((t) => Console.WriteLine("I'm done"));
Run Code Online (Sandbox Code Playgroud)
要么
await Task.Delay(1000);
Console.WriteLine("I'm done");
Run Code Online (Sandbox Code Playgroud)
对于旧框架,您可以使用以下内容:
var timer = new System.Timers.Timer(1000);
timer.Elapsed += delegate { Console.WriteLine("I'm done"); };
timer.AutoReset = false;
timer.Start();
Run Code Online (Sandbox Code Playgroud)
根据问题中的描述示例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2552 次 |
| 最近记录: |