[英]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 Task.Delay if you do not want to worry about creating a timer on your own. 如果您不想担心自己创建计时器,可以使用Task.Delay 。 See this for more information: 请参阅此以获取更多信息:
http://msdn.microsoft.com/en-us/library/hh194873.aspx http://msdn.microsoft.com/en-us/library/hh194873.aspx
http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx
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.