2011-12-31 27 views
4

怎麼可能?爲什麼?定時器只是在調用MessageBox.Show()

我有一個,如果沒有網絡連接被稱爲計時器,如方法下:

public void Foo() { 
    for (int i = 0, count = MailList.CheckedItems.Count; i < count; i++) { 
     /* Check for network available connection in computer 
       public bool HasConnection() { 
       return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); 
      }  
     */ 
     if (!net.HasConnection()) { 
       SearchNetworkConnection.Start(); //start the timer 
     } 
    } 
} 

Timer_Tick方法:

private void SearchNetworkConnection_Tick(object sender, EventArgs e) { 
      ++ATTEMPRECONNECT; 

      string currentState = "attemp reconnect.."; 
      MessageBox.Show(currentState, "..", MessageBoxButtons.OK, MessageBoxIcon.Warning); 

      if (ATTEMPRECONNECT >= ATTEMPRECONNECTLIMIT) { 
       //do abort all process 
       SearchNetworkConnection.Stop(); 
      } 
     } 

只是如果這樣的作品很奇怪,我在SearchNetworkConnection.Start()之後致電MessageBox.Show()

換句話說,這是行不通的,定時器將不會運行:

if (!net.HasConnection()) { 
     SearchNetworkConnection.Start(); 
    } 

調用MessageBox.Show(),它工作正常:

if (!net.HasConnection()) { 
     SearchNetworkConnection.Start(); 
     MessageBox.Show("lol"); 
} 

,如果它是有用的,Foo()方法運行在線程上。

我希望這很清楚。任何幫助非常感謝,提前感謝! :)

UPDATE

這樣。我認爲這是一個有點怪。我爲一些測試寫了一個簡單的代碼。我很驚訝,錯誤仍在繼續。 下來的代碼工作正常。但如果你更改順序

timer.Start(); 
DialogResult result = MessageBox.Show(text, caption); 

DialogResult result = MessageBox.Show(text, caption); 
timer.Start(); 

它不工作。定時器不啓動。

public static DialogResult Show(string text, string caption,int dellay) 
     { 

      Timer timer = new Timer(); 
      timer.Interval = dellay; 
      timer.Start(); 
      DialogResult result = MessageBox.Show(text, caption); 
      timer.Tick += new EventHandler(delegate 
      { 
        IntPtr handle = FindWindow(null, caption); 

        if (handle != IntPtr.Zero) 
        { 
         IntPtr hresult = SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); 

         if (hresult == IntPtr.Zero) 
         { 
          timer.Stop(); 
          timer.Dispose(); 
         } 
        } 
      }); 

      return result; 
     } 
+0

即使計時器已經啓動,您的'Foo'方法也會調用Timer.Start。是否有可能調用'開始'重置時間間隔?也許你應該寫'if(!net.HasConnection()&&!SearchNetworkConnection.Enabled)'。 – 2011-12-31 13:53:17

回答

4

您的計時器需要一個messagepump來運行。 MessageBox.Show()提供了一個。

但是你會想完全避免messageboxes(請看Systems.Diagnostsics.Debug.Print())。

你應該看看其他計時器(System.Threading,System.Timers)。


第2部分

幽州一個線程Foo()運行。這聽起來不錯。
但是,您的Windows.Forms.Timer需要一個MessageBox函數的事實意味着您以某種方式阻止了您的主線程。所以你的問題不在發佈的代碼中,而是在其他地方。

+1

「messagepump」..? – BlackBear 2011-12-31 12:59:06

+0

@亨克Holterman:什麼是「messagepump」?起初我試着在MessageBox之後使用Debug.WriteLine()。 我相信用.Print()方法不能有太大的不同。 – Jack 2011-12-31 13:06:31

+0

是的,你知道。'while(GetMessage()){Dispatchmessage(); ''。每個Windows應用程序都有一個,通常在'Application.Run()'內。 – 2011-12-31 13:08:36