服務(wù)熱線
153 8323 9821
請問如果我想執(zhí)行一句代碼后讓到下一句代碼的執(zhí)行時間有個間隙,
既想自己控制他在前一句代碼執(zhí)行后的多少時間后開始執(zhí)行有辦法做到么,
for(int i=0;i<10;i++)
{
Console.WriteLine("OK");
System.Threading.Thread.Sleep(2000);
}
我用這種辦法的.
C#怎樣實現(xiàn)延時執(zhí)行代碼的功能? 請高手指點:
需求如下:
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 之間加入一個延時函數(shù),即是方法1執(zhí)行完畢,過5分后再執(zhí)行方法2;
且在A用戶運行過程中,又不影響B(tài)用戶等其他用戶的操作;
一天會有幾百個用戶執(zhí)行這個流程,延時代碼該如何實現(xiàn)呢?
回答一:(這個回答得分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();
}
回答二:(這個回答得分20分)
Timer控件
Timer.Enabled 屬性用于設(shè)置是否啟用定時器
Timer.Interval 屬性,事件的間隔,單位毫秒
Timer.Elapsed 事件,達到間隔時發(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!");
}
}