C#延時函數(shù)的使用說明
更新時間:2022年04月20日 09:43:31 作者:海歌也瘋狂
這篇文章主要介紹了C#延時函數(shù)的使用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
C#延時函數(shù)使用
在線程中如果需要延時,盡量不要使用Sleep()函數(shù),這樣會導(dǎo)致時間片切到別的線程中。
使用如下函數(shù):
? ? //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個延時函數(shù)
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;
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C# Winform程序?qū)崿F(xiàn)防止多開的方法總結(jié)【親測】
這篇文章主要介紹了C# Winform程序?qū)崿F(xiàn)防止多開的方法,結(jié)合實例形式總結(jié)分析了C# Winform防止多開相關(guān)操作技巧與使用注意事項,需要的朋友可以參考下2020-03-03
淺談C#下winform和JS的互相調(diào)用和傳參(webbrowser)
下面小編就為大家?guī)硪黄獪\談C#下winform和JS的互相調(diào)用和傳參(webbrowser)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
C# Dynamic關(guān)鍵字之:dynamic為什么比反射快的詳解
本篇文章是對C#中dynamic為什么比反射快進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

