调用MessageBox.Show()时,定时器才有效

怎么可能? 为什么?

如果没有网络连接,我有一个调用的计时器,如方法down:

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(); } } 

这很奇怪,就像我在MessageBox.Show()之后调用MessageBox.Show() SearchNetworkConnection.Start()

换句话说,它不起作用,Timer将不会运行:

 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; } 

您的计时器需要一个消息泵来运行。 MessageBox.Show()提供了一个。

但是你要完全避免使用消息框(查看Systems.Diagnostsics.Debug.Print())。

你应该看看其他计时器(System.Threading,System.Timers)。


第2部分

您声明Foo()在Thread上运行。 听起来不错。
但是你的Windows.Forms.Timer需要MessageBox才能运行这一事实意味着你以某种方式阻止你的主线程。 所以你的问题不在发布的代码中,而在其他地方。