服務(wù)熱線
153 8323 9821
請(qǐng)問(wèn)如果我想執(zhí)行一句代碼后讓到下一句代碼的執(zhí)行時(shí)間有個(gè)間隙,
既想自己控制他在前一句代碼執(zhí)行后的多少時(shí)間后開(kāi)始執(zhí)行有辦法做到么,
for(int i=0;i<10;i++)
{
Console.WriteLine("OK");
System.Threading.Thread.Sleep(2000);
}
我用這種辦法的.
C#怎樣實(shí)現(xiàn)延時(shí)執(zhí)行代碼的功能? 請(qǐng)高手指點(diǎn):
需求如下:
A用戶-->執(zhí)行方法1-->執(zhí)行方法2-->執(zhí)行方法3-->流程結(jié)束;
B用戶-->執(zhí)行方法1-->執(zhí)行方法2-->執(zhí)行方法3-->流程結(jié)束;
.
.
.
N用戶-->執(zhí)行方法1-->執(zhí)行方法2-->執(zhí)行方法3-->流程結(jié)束;
想在方法1 , 方法2,方法3 之間加入一個(gè)延時(shí)函數(shù),即是方法1執(zhí)行完畢,過(guò)5分后再執(zhí)行方法2;
且在A用戶運(yùn)行過(guò)程中,又不影響B(tài)用戶等其他用戶的操作;
一天會(huì)有幾百個(gè)用戶執(zhí)行這個(gè)流程,延時(shí)代碼該如何實(shí)現(xiàn)呢?
回答一:(這個(gè)回答得分10分)
Thread.Sleep()延遲
或多線程class Test
{
public static Int64 i = 0;
public static void Add()
{
for (int i = 0; i < 100000000; i++)
{
Interlocked.Increment(ref Test.i);
}
}
public static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(Test.Add));
Thread t2 = new Thread(new ThreadStart(Test.Add));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine(Test.i.ToString());
Console.Read();
}
回答二:(這個(gè)回答得分20分)
Timer控件
Timer.Enabled 屬性用于設(shè)置是否啟用定時(shí)器
Timer.Interval 屬性,事件的間隔,單位毫秒
Timer.Elapsed 事件,達(dá)到間隔時(shí)發(fā)生。
例子:
public class Timer1
{
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 5 seconds.
aTimer.Interval=5000;
aTimer.Enabled=true;
Console.WriteLine("Press \ q\ to quit the sample.");
while(Console.Read()!= q );
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
}