简体   繁体   English

如何延迟在C#中执行的代码

[英]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. 我正在为我的C#控制台程序编写一个简单的许可证系统脚本,并且试图延迟执行代码。

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. 我对C#不太满意,但是我知道一些基础知识。

You can use the Timer class to generate an event after a certain period. 您可以使用Timer类在一定时间后生成事件。 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. 其中1000是时间延迟。

This code starts Timer with initial delay, when time elapses TimerCallback will be called asynchronously. 此代码以初始延迟启动Timer ,当时间过去时, TimerCallback将被异步调用。 Period Infinite means that callback will be called only once. Period Infinite意味着回调将仅被调用一次。 This will not stop executing current thread, so if you want to stop current thread then better use Threat.Sleep : 这不会停止执行当前线程,因此,如果要停止当前线程,则最好使用Threat.Sleep

Thread.Sleep(1000);
// your code

Add the following before executing code. 在执行代码之前添加以下内容。 1000 for each second to wait. 每秒等待1000。

Thread.Sleep(1000); 

You can use one of following methods: 您可以使用以下方法之一:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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