这篇文章主要介绍了C#延时函数的使用说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
C#延时函数使用
在线程中如果需要延时,尽量不要使用Sleep()函数,这样会导致时间片切到别的线程中。
使用如下函数:
//Delay function
public static void Delay(int milliSecond)
{
int start = Environment.TickCount;
while (Math.Abs(Environment.TickCount - start) < milliSecond)
{
Application.DoEvents();
}
}
或者:
//Delay us Create a waitable timer
[DllImport("kernel32.dll")]
public static extern int CreateWaitableTimer(int lpTimerAttributes,
bool bManualReset, int lpTimerName);
public static void UsDelay(int us)
{
long duetime = -10 * us;
int hWaitTimer = CreateWaitableTimer(NULL, true, NULL);
SetWaitableTimer(hWaitTimer, ref duetime, 0, NULL, NULL, false);
while (MsgWaitForMultipleObjects(1, ref hWaitTimer, false, Timeout.Infinite,
QS_TIMER)) ;
CloseHandle(hWaitTimer);
}
C#3个延时函数
public static void Delays(int DelayTime = 100)
{
int time = Environment.TickCount;
while (true)
{
if (Environment.TickCount - time >= DelayTime)
{
break;
}
Application.DoEvents();
Thread.Sleep(10);
}
}
public static void Delay1(int milliSecond)
{
int start = Environment.TickCount;
while (Math.Abs(Environment.TickCount - start) < milliSecond)
{
Application.DoEvents();
}
}
//延时程序 秒
public static bool Delay2(int delayTime)
{
DateTime now = DateTime.Now;
int s;
do
{
TimeSpan spand = DateTime.Now - now;
s = spand.Seconds;
Application.DoEvents();
}
while (s < delayTime);
return true;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#延时函数的使用说明


基础教程推荐
猜你喜欢
- Unity shader实现高斯模糊效果 2023-01-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C# 解析XML和反序列化的示例 2023-04-14
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#中 Json 序列化去掉null值的方法 2022-11-18