使用Thread.Sleep()显示缓慢的模拟 [英] Show a slow simulation using Thread.Sleep()

查看:166
本文介绍了使用Thread.Sleep()显示缓慢的模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lbl1.BackColor = Color.Red;    //change backcolors of labels
lbl2.BackColor = Color.Red;
Thread.Sleep(2000);

lbl1.Text = val1.ToString(); //assign values to labels
lbl2.Text = val2.ToString();
Thread.Sleep(2000);

lbl1.BackColor = Color.Green; //reassign original backcolors
lbl2.BackColor = Color.Green;

这是递归方法内部称为方法的一部分.我想分解这些步骤以显示缓慢的模拟.但是,这没有给出预期的输出.

This is a part of a method called inside a recursive method. I want to break down these steps to show a slow simulation. But, this doesn't gives the expected output.

有更好的方法吗?请提出建议.

Is there a better way? Please suggest.

推荐答案

不要使用Thread.Sleep(),因为它会冻结UI,而您可以通过实现自己的 Asynchronous 方法来完成相同的工作

Don't use Thread.Sleep() as it freezes the UI, rather you can do the same work by implementing your own Asynchronous method.

您还可以通过使用

You can also achieve the same by using Timers.

这是有关如何异步管理任务的示例. 假设这是我的方法Perform()

This is an example on how to manage tasks asynchronously. Suppose, this is my method Perform()

private async Task Perform()
{
    lbl1.BackColor = Color.Red;    
    lbl2.BackColor = Color.Red;
    await Task.Delay(2000);

    lbl1.Text = val1.ToString();  
    lbl2.Text = val2.ToString();
    await Task.Delay(2000);

    lbl1.BackColor = Color.LightSeaGreen;  //changed to lightseagreen as the green you used
    lbl2.BackColor = Color.LightSeaGreen;  //was hurting my eyes :P
}

我在一个事件中称它为button_click事件.

and I call it in an event say, on a button_click event.

private void button1_Click(object sender, EventArgs e)
{
    Task t = Perform();
}

输出将类似于:

                                                       The output will be like:

详细了解如何使用 异步并等待 .

Learn more on how to use async and await.

这篇关于使用Thread.Sleep()显示缓慢的模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆