2013-03-05 42 views
-5

我正在使用套接字編程,我可以在一些時間間隔(如10秒)後檢查用戶的實時連接。但目前,我不知道。我將如何去做。需要定時器在C#中運行10秒後,才能運行#

請幫幫我。我將非常感激。

+1

請閱讀[常見問題]和[問] – 2013-03-05 14:45:25

+0

如果您必須定期檢查,使用Timer類將會比擁有睡眠線程更好的解決方案 – 2013-03-05 14:46:53

回答

2

包括:using System.Threading;

我不知道你在做什麼(有代碼來告訴我們?),但這裏的一般邏輯:

while (/*connection is active*/) 
{ 
//check connection 
Thread.Sleep(10000); //10 seconds 
} 
+1

我會將'Sleep'分成長度較小的環,並帶有退出檢查。 – Sinatr 2013-03-05 14:55:48

+0

嗯,好點。 – 2013-03-05 15:01:00

2

從MSDN Timer Class (System Timers)

以下是來自MSDN頁面的一個例子

[C#] 
public class Timer1 
{ 
    public static void Main() 
    { 
     System.Timers.Timer aTimer = new System.Timers.Timer(); 
     aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent); 
     // Set the Interval to 10 seconds. 
     aTimer.Interval=10000; 
     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!"); 
    } 
} 
1

它真的取決於你在做什麼,以及你如何檢查連接。

您可以使用Threading.sleep();一個計時器,或取決於你在做什麼,你可能能夠使用基於連接/斷開連接的事件處理程序...

相關問題