C# on .net Mobile Framework - Windows form property won't change
I'm writing a c# application that requires user authentication.
When开发者_高级运维 the user hits the log in button, quite a bit of stuff is done in the background, but I'm having trouble informing the user that something is happening, and that the program isn't just frozen.
I have some hidden text fields that I would like to have show up after they log in, while this stuff is running, but I can't seem to get it to show up.
Basically, when the user hits the log in button, it checks to see if their credentials are correct, then the messages should show up, and then either some other functions might run, followed by a different form being shown.
After the credentials are checked, and I know that the user is valid, I tried running this:
please_wait.Visible = true;
But it doesn't change when it gets to that point in the code. I've tried threading it, to see if that would help. Instead of calling the above line, I just start a thread that does it.
That doesn't work either. The field still doesn't show up.
If I return out of the function right after I either start the thread or change the Visible property, it works just fine.
How do I get it to work fine and have more code run after the change?
The problem isn't that you need to update the UI from a background thread. Rather, it's that you should be performing your long-running task in a background thread and marshalling updates to the foreground. This is frequently done via a BackgroundWorker
with progress notification (on a progressbar, for example).
Basically, your UI foreground thread is either loaded or blocked doing work, so it isn't handling messages in its message queue to update your user interface.
Along with what Greg recommends (which is certainly the first step if you're not already doing it) you may also need to give up some quantum.
If you are taxing the scheduler, it's possible that the UI updates (which are pretty low priority) may be getting preempted until your worker is complete. Adding an Application.DoEvents (or maybe Thread.Sleep(1) in the background thread) could give the UI a little scheduler time to paint.
Have you tried adding a call to Application.DoEvents()? It's a hack, but it's all you sometimes need.
精彩评论