C#中的延迟功能 [英] Delay function in C#
问题描述
我需要了解如何在一组命令之间创建延迟.我的背景是C(DOS),现在在Visual Studio 2015中使用C#恢复了这些概念.这是我正在努力的代码:
I need to understand how can I create delays between a set of commands. My background is with C (DOS) and now reviving the concepts using C# in Visual Studio 2015. This is the code I am struggling with:
using System.Threading;
private void button1_Click(object sender, EventArgs e) // Button
{
int i;
for (i = 0; i < 10; i++)
{
textBox1.BackColor = Color.Red;
Thread.Sleep(100);
textBox1.BackColor = Color.Yellow;
Thread.Sleep(100);
}
}
我期望文本框的背景颜色会交替更改10次,但是在循环结束后我只能看到黄色.如果增加延迟,我确实会注意到该程序需要一些时间才能完成.我浏览了一些相关文章,但没弄明白这一点.任何帮助将不胜感激.谢谢
I was expecting the background color of the textbox will change alternatively 10 times but I could see only yellow color after the loop finishes. If I increase delay I do notice that program takes time to finish. I went through some related articles but couldn't get the point. Any help will be appreciated. Thanks
推荐答案
使用异步方法通过内置的 Task.Delay
方法创建延迟.这将导致执行被暂停,然后在指定的时间后结束之后恢复执行.
Use an async method to create a delay using the built-in Task.Delay
method. This will cause execution to be paused and then resumed after the specified time without blocking the current thread.
async Task UseDelay()
{
await Task.Delay(1000); // wait for 1 second
}
根据您的具体情况
async void button1_Click(object sender, EventArgs e)
{
for (var i = 0; i < 10; i++)
{
textBox1.BackColor = Color.Red;
await Task.Delay(100);
textBox1.BackColor = Color.Yellow;
await Task.Delay(100);
}
}
这篇关于C#中的延迟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!