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# 使用谷歌身份驗證GoogleAuthenticator的示例
這篇文章主要介紹了c# 使用谷歌身份驗證GoogleAuthenticator的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01
C#自定義繁體和簡體字庫實現(xiàn)中文繁體和簡體之間轉(zhuǎn)換的方法
這篇文章主要介紹了C#自定義繁體和簡體字庫實現(xiàn)中文繁體和簡體之間轉(zhuǎn)換的方法,通過自定義繁簡轉(zhuǎn)換字庫實現(xiàn)繁體與簡體轉(zhuǎn)換的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
C#實現(xiàn)軟件開機自動啟動的兩種常用方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了C#實現(xiàn)軟件開機自動啟動的兩種常用方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解一下2023-07-07

