简体   繁体   中英

How to delay code being executed in C#

I am coding a simple licence system script for my C# console program, and I am trying to delay the code being ran.

Task ShutdownTask = new Task(SilverEnvironment.PerformShutDown);
                            ShutdownTask.Start();
                            SilverEnvironment.GetGame().GetModerationTool().LogStaffEntry("SERVER", string.Empty, "Shutdown", "Invalid licence provided.");

That is the code that I want excecuted in a timed matter, instead of being ran right away. I am not too good with C#, but I know the basics.

You can use the Timer class to generate an event after a certain period. Don't forget to disable the timer, otherwise it will repeat the event after the same interval.

new System.Threading.Timer(new TimerCallback((obj) => {
    // your code
}, null, 1000, System.Threading.Timeout.Infinite);

where 1000 is the time delay.

This code starts Timer with initial delay, when time elapses TimerCallback will be called asynchronously. Period Infinite means that callback will be called only once. This will not stop executing current thread, so if you want to stop current thread then better use Threat.Sleep :

Thread.Sleep(1000);
// your code

Add the following before executing code. 1000 for each second to wait.

Thread.Sleep(1000); 

You can use one of following methods:

1) Thread.Sleep(5000); OR 2) await Task.Delay(5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM