(WPF) We have been asked to build a little window that pops up when the app is busy (instead of or in addition to a wait cursor). We put a textblock in the window, and a ProgressBar with IsIndeterminate = true.
We call show on the little window, and then start up our long-running process, calling Close on the little window when we are through. However, during the long-running process, the ProgressBar does not show any activity, and the little window shows (Not Responding) in its title.
Is this even possible? A better idea?
You need to look into using another thread (or multiple threads) to do the heavy processing that could take longer than 100ms (100ms and above can cause this 'hanging' appearence before 'Not Responding' appears.)
You could create a new thread using a BackgroundWorker
object and subscribe to the OnProgressChanged event to indicate a progress bar update. This does not however get around the problem of accessing the main (UI) threads Progress Bar. You would have to check if an Invoke is required and then invoke a piece of code responsible for updating the Progress Bar.
Here is a StackOverflow question that shows a nice Extension Method in the accepted answer for invoking a method call on a control:
Invoking
Hopefully that helps!!
The problem is most likely that whatever is causing the app to be "busy" is being run in the main thread of the app. So, the app stops responding, including responding to layout and painting requests from the OS. So, when the app is "busy", it's too busy to paint the new window.
The solution is to move as much "heavy lifting" as possible into background threads, so the main thread and thus the UI remain responsive.
Related
I have a program which does some copy jobs (via File.Copy) that could last a few minutes. When the user brings another window to foreground in this time the program window gets blank since it doesn't redraw itself.
Now I want to show a ProgressBar in an extra window in the center of the screen, but that window get's blank too.
So I startet it in another thread which didn't help.
I'm quite sure someone did this before but I cannot find a working example. Any Ideas?
There is nice example in the documentation on BackgroundWorker class.
ChrisF is correct. Your long operation should be done in a BackgroundWorker thread. You can use BackgroundWorker to report progress, and hook that up to a progress bar on your form.
You need to thread your operation using a BackgroundWorker. There are other ways to thread the operation, but this one is probably the simplest, and will continue to perform message pumping in the foreground so Windows doesn't think your application has stopped responding.
Another option would be to use a Thread, and use Thread.Join to wait for the background task to complete, since Thread.Join also sends standard message pump information to Windows while it waits.
You can use BackgroundWorker class.
See this answer.
apologies if I don't explain this clearly, but I'm writing an app which is causing me some problems with threading.
I have a UI which starts a System.Timers.Timer. Each time this timer elapses it triggers a workflow which opens a progress screen. To prevent another workflow starting before the last one has finished it locks an object on the main form.
This progress screen starts and reports the progress of, some file copying using FileCopyEX.
The problem I'm having is that the progress screen does not display until after the work flow has been completed.
Hopefully this will make it clearer:
Main Form
|
Timer Elapses
|
WorkFlow Starts
|
Progress Screen opens (errors which occur go back to the previous)
|
File copying occurs (progress reported back to progress screen)
If no errors, returns to main screen before next tick.
Until now I've only implemented very simple threading, so I'm not sure how best to implement this. I've tried starting the workflow on a BackGroundWorker to seperate it from the UI thread but it behaves the same.
Thanks
I suggest that you read about the BackgroundWorker. This has hooks for reporting progress.
Remember that system timers invoke its event handler on a non-UI thread. Whenever, you do something with the UI you must be on the UI thread.
Without the code I can only guess at the cause, but the likely reason is that the Progress window needs the UI to be pumping messages to appear - i.e. the UI thread needs to be running.
If the UI thread is busy running your workflow, then it won't get around to processing the displaying of your window until after that. You need to separate your flow so that the progress window is on your UI thread and the workflow is on a background thread.
Hope that makes sense!
K I am looking at a primarily single thread windows forms application in 3.0. Recently my boss had a progress dialogue added on a separate thread so the user would see some activity when the main thread went away and did some heavy duty work and locked out the GUI.
The above works fine unless the user switches applications or minimizes as the progress form sits top most and will not disappear with the main application. This is not so bad if there are lots of little operations as the event structure of the main form catches up with its events when it gets time so minimized and active flags can be checked and thus the dialog thread can hide or show itself accordingly.
But if a long running sql operation kicks off then no events fire. I have tried intercepting the WndProc command but this also appears queued when a long running sql operation is executing. I have also tried picking up the processes, finding the current app and checking various memory values isiconic and the like inside the progress thread but until the sql operation finishes none of these get updated. Removing the topmost causes the dialog to disappear when another app activates but if the main app is then brought back it does not appear again.
So I need a way to find out if the other thread is minimized or no longer active that does not involve querying the actual thread as that locks until the sql operation finishes.
Now I know that this is not the best way to write this and it would be better to have all the heavy processing on separate threads leaving the GUI free but as this is a huge ancient legacy app the time to re-write in that fashion will not be provided so I have to work with what I have got.
Any help is appreciated
It sounds as if the long running operation is bound to the progress dialog? That's usually a bad idea and I wonder whether the progress can be showed at all.
However you should consider using a BackgroundWorker for your long running operations. So your GUI (the main form as well as the progress dialog stays alive).
This way you should be able to send the minimize event of the main form to the progress dialog which can react to it instantly.
Btw. the BackgroundWorker supports progress reports on its own.
I'm building a UI for a program, and I can't figure out why my progress bar won't become visible after the convert button is clicked.
private void convertButton_Click(object sender, EventArgs e)
{
toolStripProgressBar.Visible = true;
...
toolStripProgressBar.Visible = false;
}
I ran into a similar problem with tkinter in Python, and I had to call a function to update the idle tasks. Is there a way to do this with windows forms without using threads?
Edit: On a side note, this is a progress bar in a toolStrip that also contains a label that gets updated with status bar text. Is there any way to get the label on the left side and the progress bar on the other instead of right next to each other on the left?
Well, there is a way to do this without using threads (Application.DoEvents) but I strongly recommend against you using it. Re-entrancy is nasty, and you really don't want the UI thread tied up at all.
Use BackgroundWorker instead - it's easy, and it's pretty much designed for progress bars. It takes the hassle out of using a separate thread and reporting progress back to the UI thread. No need for Control.Invoke etc - it takes care of that for you.
There are lots of tutorials for BackgroundWorker - it shouldn't take you too long to get going with it.
Per the question you asked for the way to do this WITHOUT threads, that is to do it with Application.DoEvents();. (Just add that call right after setting the progress bar as visible.)
Now I do agree with Jon Skeet though that BackgroundWorker is a better way of doing this, but it does use a separate thread.
You need to execute your process in a thread separate from the UI thread, and then have it periodically report back to the UI thread with it's progress. If your convert operation is working inside the UI thread, it will simply go unresponsive until the operation is complete.
The progress bar can only become visible when it is allowed to paint which occurs during the processing of messages. Message processing cannot normally happen while you are in the middle of an event handler. If you want the progress bar to show up you will have to set the visiblitity to true, start a background thread to complete the work and return from the handler.
I'm guessing the problem is that the "..." in your code is a long-running process. UI updates are not instantaneous, but must run through the message queue in windows and then be painted to the screen. The queue is pumped and painting takes place in the same thread as your events.
As a result, any long-running tasks need to be moved to a different thread. More than that, your line line of code needs to called after that thread terminates. Otherwise you set the progress bar and then immediately turn it off again.
One way to do that is with a BackgroundWorker control.
Here go two links trying to explain you how things work:
(1) (2)
Now, I will try to explain it as shortly as I can. Most of what happens inside a windows forms application happens in a single thread, usually the same thread Main() runs in. If you open Program.cs, you will see that Main() has a line that looks like the following:
Application.Run(new Form1());
If you debug the application at any moment and examine the call stack, you will see it will trace back to that Run method. This means that a Windows Forms application is in fact a continuous run of the Run method. So, what is Run doing? Run is eating a message queue through which Windows sends messages to it. Run then dispatches those messages to the correct controls, which themselves do things like add text which corresponds to the key being pressed, redraw themselves, etc. Notice that all this happens during and endless loop running alongside a single thread, so weather you are typing or simply moving the window around, loads of those messages are being passed onto the application, which in turn is processing them and reacting accordingly, all in that single thread. Controls can also send messages to themselves through the queue and even you can place messages in the pump via Control.BeginInvoke. One of the things those controls do is to raise events according to what happens. So, if you click a button, the code you've written to handle that click will ultimately and indirectly be run by the Application.Run method.
Now, what is happening with your code is that even though you are changing the visible status of your progress bar to visible and then updating its Value, you are then changing its visibility to false, all in the same method. This means that only after you leave the method, will Application.Run() be able to continue iterating and consuming the message queue, effectively asking the progress bar to update its display. When that happens, you've already left the progress bar's visibility to false, the last thing you did before exiting the method. DoEvents() is a quick and dirty workaround to your problem as it reads the messages in the queue and processes them. I don't really feel comfortable using it as it can bring reentrancy problems.
Using threads is a good solution, but I would recommend using a ThreadPool thread instead of a custom thread in this kind of situation, as I tend to use custom threads only in cases where I have a limited number of long lived threads and I need to control their life cycles. The easiest and most practical way to use threads is to use the BackgroundWorker component, even though I would recommend going through the pains of understanding how to do Windows Forms multithreading with delegates if you want to really understand what is going on.
My solution is to call refresh on the status strip.
I believe this causes the UI thread to repaint the status strip.
toolStripStatusBar1.PerformStep();
statusStrip1.Refresh();
This is for .NET 4.0. Even though this question is old it was the first I found on googling this issue.
I have a form with buttons, textBoxes and userControls on it. When a button is clicked, it calls a method in another class. In this class a Message box opens. When user clicks OK, the messageBox closes, and the class method proceeds for 10 or so seconds before ending. During this 10 seconds, what ever textBox, or button the message box was over still displays the messageBox (They are not getting repainted).
The question is how can I force everything to repaint on the form. The problem is the class that has the messageBox does not have any knowledge of the form that called it
Frank
You can try with
Application.DoEvents()
right after the message box closes. However - unless you execute the method that you are calling in that other class in a background thread - your UI will not be responsive for 10 seconds.
Is that 10 seconds spent doing work entirely in the UI? If not, it should really be done on a separate thread. Even if you refresh the form itself, you're still going to have a unresponsive UI for 10 seconds, which isn't ideal.
See my threading tutorial for an example of executing code in a different thread and calling back to the UI thread. Be aware that this is the "old" way of doing things - BackgroundWorker makes things somewhat simpler.
The problem here is that you have processing that is occurring on the UI thread and blocking the paint message. Calling Refresh or Invalidate isn't going to fix this, as you are still blocking on the thread that would perform those operations.
Rather, you should take that processing and move it to another thread, and then update your UI thread (appropriately, through the Invoke method, more likely than not) as you perform the work on the background thread.
To force everything to repaint you can call Invalidate() on the main form.
Your problem is that you are doing your work on the UI thread. The UI will not get repainted until your method returns which will allow the Windows message loop to continue.
The solution is to run your work method on a different thread. Perhaps the BackgroundWorker class will solve your problem nicely.
Edit:
See this article for an in depth explanation:
http://www.yoda.arachsys.com/csharp/threads/winforms.shtml