如何在.net中将进程保留2-3秒? [英] How to hold the process for 2-3 second in .net?

查看:74
本文介绍了如何在.net中将进程保留2-3秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有布尔变量.我有基于此布尔值的计时器.两者都是不同的形式.初始化表单时,布尔值为True.在特定条件下将其设置为false.我想在设置为false之前搁置2-3秒.

I have Boolean variable. I have timer which is based on this Boolean value. Both are in different form. Boolean is True when form is initialize. It set false on a specific condition. I want to put 2-3 second hold before it set to false.

//Form 1

Private void updateGrid()
{
    if(Form2.isBooleanTrue)
    {
        //Code to execurte
    }
}


//Form 2
public static isBooleanTrue = false;
Private void checkCondition()
{
    // I want to hold here. Note it should not hold the Form1 process
    isBooleanTrue = true;
}

有人可以建议我在布尔值设置为false之前如何保持该过程吗?因此,计时器可以再运行几秒钟.

Can any body suggest me how to hold the process before Boolean set false? So, timer can run for few more seconds.

推荐答案

如果使用C#5或更高版本运行.NET 4.5或更高版本,则可以使用异步/等待功能.

If you're running .NET 4.5 or later with C#5 or later you can use the async/await feature.

将您的方法标记为async,并(如果可能,不是必需的,但建议)将其返回类型更改为 Task.Delay 使您的UI线程等待您想要的时间.

Mark your method as async and (if possible, not necessary but recommended) change it's return type to Task. Then, you can use Task.Delay to make your UI thread wait for however long you want.

重要的一点是它将异步地等待 ,因此不会冻结UI,这与您使用

The important bit is it will wait asynchronously, and so it won't freeze your UI, unlike if you used for example Thread.Sleep, instead it will return from your method and continue execution of other code. After 3 seconds, it will run the remainder of the method as a task continuation, which will update your isBooleanTrue field.

您的方法现在应如下所示:

Your method should now look like this:

private async Task checkCondition() // If you can't change the return type you can leave it as void, although it's not recommended.
{
    await Task.Delay(3000);
    isBooleanTrue = true;
}

请注意,即使返回类型为Task,该方法也不会返回任何内容.这是新的async/await语法的功能,返回的Task将自动生成.

Note that the method doesn't return anything, even though the return type is Task. This is a feature of the new async/await syntax, the returning Task will be generated automatically.

您可以在此处了解更多信息.

You can read more about it here.

这篇关于如何在.net中将进程保留2-3秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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