2013-01-04 95 views
-2

我想暫停C#程序幾秒鐘,我不想使用system.threading.thread.sleep,有沒有其他方法來暫停程序。暫停c#程序幾秒鐘?

我想顯示一些秒的窗口並自動最小化。 我增加了兩個定時器,一個用於最大化窗口,一個用於最小化; 當窗口最大化我想呆在那裏幾秒鐘,如果我使用睡眠方法它不顯示窗體上的文本。所以有什麼方法可以暫停窗口幾秒鐘。

+3

定義你的意思是「暫停」。如果睡眠不是你的意思,我不知道你的意思。 –

+3

爲什麼你不想叫'睡眠'? –

+0

如果您不想使用睡眠,請使用計時器。 –

回答

1

我想,如果你不想使用Sleep唯一剩下的就是用計時器這樣的:

System.Timers.Timer timer1= new System.Timers.Timer(1000); 
timer1.Elapsed += new ElapsedEventHandler(maximizeScreen); 
timer1.Start(); 

private void maximizeScreen(object source, ElapsedEventArgs e) { 
    //Do the maximizing 

    //disable the timer 
    ((System.Timers.Timer)source).Stop(); 

    System.Timers.Timer timer2= new System.Timers.Timer(2000); 
    timer2.Elapsed += new ElapsedEventHandler(minimizeScreen); 
    timer2.Start(); 
} 

private void minimizeScreen(object source, ElapsedEventArgs e) { 
    //Do the minimizing 

    //disable the timer 
    ((System.Timers.Timer)source).Stop(); 
} 
0

你可能有怎樣的一個閃屏等。這是一個簡單的Windows窗體,它顯示一些文本消息並保持打開一段時間:

public partial class WaitWindow : Form 
{ 
    System.Windows.Forms.Timer timer; 

    public WaitWindow(int interval) 
    { 
     InitializeComponent(); 

     this.Shown += new EventHandler(WaitWindow_Shown); 

     timer = new Timer(); 
     timer.Interval = interval; 
     timer.Tick += new EventHandler(timer_Tick); 
    } 

    void WaitWindow_Shown(object sender, EventArgs e) 
    { 
     timer.Start(); 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     timer.Stop(); 
     this.Close(); 
    } 
} 

它使用計時器在給定時間段內關閉。至少你可以使用這樣的:

new WaitWindow(1000).ShowDialog(); 

在談到Windows窗體,它更適合使用System.Windows.Forms.Timer爲:

這個計時器在Windows中使用優化的窗體應用程序和 必須在窗口中使用。

System.Timers.Timer

基於服務器的定時器是專爲在 多線程環境中工作線程使用。

1

如果您使用.NET 4.5,您可以使用Delay methodTask class等待的時間預定量,像這樣:

private async void MaximizeScreenAsync(CancellationToken cancellationToken) 
{ 
    //Do the maximizing 

    // Hold off for two seconds. 
    await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken); 

    // Minimize the screen. 
} 

注意使用cancellationToken參數,如果需要,您可以通過CancellationToken structure(從CancellationTokenSource創建)取消此操作。

該方法假定您手動觸發屏幕顯示。

async/await這裏的關鍵字將確保調用await Task.Delay運行在正確的SynchronizationContext後的代碼(如果您正在執行的UI操作如最小化和最大化窗口,它是非常重要的。另外請注意,這是而不是這種情況下,如果您撥打ConfigureAwait methodTask上的參數爲false,則返回Task.Delay)。

請注意,由於MaximizeScreen標記爲async,因此一旦呼叫到達async Task.Delay,將立即返回,因此您不應期望屏幕在完成時最小化。

如果你想等到屏幕完成,那麼我建議你公開一個任務並等待它。

首先,修改簽名返回一個Task(沒有別的變化):

private async Task MaximizeScreenAsync(CancellationToken cancellationToken) 

,然後在調用點,只是呼籲TaskWait method返回(使用相同的CancellationToken,你會傳遞到MaximizeScreenAsync):

MaximizeScreenAsync(cancellationToken).Wait(cancellationToken); 
+0

你需要建立取消到這個(並不是很難做到這一點);它似乎是一個商業案例,可以取消定時器。 – Servy

+0

@Servy更新爲包含取消。感謝您的高舉。 – casperOne