The timer just works if MessageBox.Show () is called

How is this possible? I have a timer that is called if there is no network connection, as in the down method:

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

and _Tick Timer method:

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

This works weirdly only if I call MessageBox.Show() after SearchNetworkConnection.Start() .

In other words, this does not work, the timer will not work:

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

MessageBox.Show() calling MessageBox.Show() , it works fine:

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

if this may be useful, the Foo() method is run in the thread.

Refresh

So I think this is a little strange. I wrote simple code for some tests. and I am surprised the error continues. The code below works fine, but if you change the order

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

in

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

this does not work, the timer does not 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; } 
+4
source share
1 answer

Your timer requires a message to start. MessageBox.Show () provides one.

But you don’t want to bypass mailboxes at all (see System.Diagnostsics.Debug.Print ()).

You should probably look at other timers (System.Threading, System.Timers).


Part 2

You indicate that Foo() running in a thread. That sounds normal.
But the fact that your Windows.Forms.Timer needs a MessageBox function means that you are somehow blocking your main thread. Therefore, your problem is not in the hosted code, but in another place.

+4
source

Source: https://habr.com/ru/post/1388726/


All Articles