MessageBox.Show and program behaviour

  • Thread starter Thread starter Nuno Magalhaes
  • Start date Start date
N

Nuno Magalhaes

Why does the MessageBox.Show function in the thread below changes the
program behaviour, in other words, the APListView becomes filled with
values with a call to RefreshAPListView. Without the MessageBox.Show
function, in my laptop, the code doesn't get past the inner loop where
there is a Thread.Sleep(10).

Here is the code. Does anyone know why? Thanks.

private void APRun()
{
while(true)
{
//Get apData info
AP_DATA[] apData=null;
while(true)
{
apData=Wrapi.GetAPList();
if(apData.Length!=0)break;
else Thread.Sleep(10);
}
UpdateTotalAPDataList(apData);
RefreshAPListView();
//Sleep thread
Thread.Sleep(1000);
//This loop can or cannot be here
MessageBox.Show("Loop mark");
}
}
 
Why does the MessageBox.Show function in the thread below changes the
program behaviour, in other words, the APListView becomes filled with
values with a call to RefreshAPListView. Without the MessageBox.Show
function, in my laptop, the code doesn't get past the inner loop where
there is a Thread.Sleep(10).

Your code is just an infinite loop where you fill your APListView, then
sleep then fill your APListView again, then sleep... This means that
without that call to MessageBox.Show, the UI thread (in which you are
executing your loop i suppose) never gets a chance to process the pending
(painting) messages in its message queue. Therefore, even though your
APListView is effecively filled, it never gets painted because you are not
letting it time to paint itslef.

When you call MessageBox.Show, the UI thread sits there doing nothing until
your click OK to close the MessageBox, which lets it time to process its
message queue messages and to paint your APListView. If you want to force
the UI thread to process all pending messages in the message queue (and
therefore force it to paint your APListView), call Application.DoEvents().
But it doesn't seem a good idea to me to put the UI thread to sleep anyway
as whenever the UI thread is sleeping, your whole UI is frozen, preventing
the user from moving, resizing or using it.
 
I don't think so. I always coded with threads and a sleep sets the
process into the queue process but a .DoEvents get's always called
whenever the process gets back in action.
By the way, I don't think I'm getting the error now, even without the
MessageBox.Show.
 
Back
Top