2014-07-18 129 views
0

最初我的代碼有Timer,它會持續ping服務器以查看它是否已連接。但是,我也有一個Timer爲了顯示當前時間。這就是它看起來像原來:BackgroundWorker和計時器問題 - UI凍結

public Main() 
{ 
    /* let's check if there is a connection to the database */ 
    isDbAvail = new Timer(); 
    isDbAvail.Interval = 8000; 
    isDbAvail.Tick += new EventHandler(isOnline); 
    isDbAvail.Start(); 

    /* the clock */ 
    clock = new Timer(); 
    clock.Interval = 1000; 
    clock.Tick += new EventHandler(clockTimer_Tick); 
    clock.Start(); 
} 

private void isOnline(object sender, EventArgs e) 
{ 
    Connection connection = new Connection(); 
    changeStatus(connection.isDbAvail()); 
} 

private void clockTimer_Tick(object sender, EventArgs e) 
{ 
    clock.Text = DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss"); 
} 

到現在爲止,一切運行良好,除了一個事實,即當它來檢查數據庫,整個UI將凍結,並會滯後約3秒鐘。我做了一些研究,發現BackgroundWorker的改變了一切以下:

public Main() 
{ 
    isDbAvail = new BackgroundWorker(); 
    isDbAvail.DoWork += isOnline; 

     /* the clock */ 
    clock = new Timer(); 
    clock.Interval = 1000; 
    clock.Tick += new EventHandler(clockTimer_Tick); 
    clock.Start(); 
} 

private void isOnline(object sender, DoWorkEventArgs e) 
{ 
    while (true) 
    { 
     Thread.Sleep(8000); 
     Connection connection = new Connection(); 
     changeStatus(connection.isDbAvail()); 
    } 
} 

當我運行它,什麼也沒有發生,我沒有得到任何錯誤。我很確定這裏有一些非常重要的東西,我似乎無法理解。

回答

0

添加

isDbAvail.RunWorkerAsync(); 

isDbAvail.DoWork 

+0

大聲笑,很好,很容易。 – Dimitri