How to hold the process for 2-3 second in .net?

拥有回忆 提交于 2019-12-25 17:03:38

问题


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;
}

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


回答1:


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

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.

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;
}

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.




回答2:


You can use Thread.Sleep, which suspends current thread for given period of time.

Thread.Sleep(3000); // 3 sec wait.

Update

To leave the UI responding and get updates after few seconds you can do below.

this.Invoke((MethodInvoker)delegate {

    Thread.Sleep(3000); 
    // run your code on UI thread
});

Another option, start asynchoronous Task that performs your action.

Task.Factory.StartNew(()=>
{
    Thread.Sleep(3000); // wait 3 secs
    form1.Invoke(new Action(()=> 
               {
                    // your logic goes here.
               }));
});


来源:https://stackoverflow.com/questions/35814329/how-to-hold-the-process-for-2-3-second-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!