Showing a wait dialog while doing interface operations in C#
So I need to do heavy interface operations in my program... More specifically, populating a Windows Forms list view and generating images on the fly. This cannot be done on an开发者_Python百科other thread.
So how do I show a modal, working (responding) dialog over my main WPF window? The dialog can be either WPF or winforms, I don't care, I'll adapt...It must be usable and always stay above and modally block it's owner form.
Just implement a dialog and call it using .ShowDialog() inside your time-consuming function. Wherever you have your time-consuming loop, call Application.DoEvents() every once in a while to allow the dialog box to show and update. Careful with this approach, though...
Be careful because if, for instance, you are handling a Paint event, and then you call Application.DoEvents() you might enter the Paint event handler twice, which is not desirable.
On a WPF window or WinForm place an image and insert this: http://www.hindustantimes.com/images/loading_gif.gif which will automatically get animated. Show the windows using .ShowDialog(OwnerWindow)
thus it will always remain on top of it's owner windows.
If you are fine with calling Application.DoEvents and it works, then that is surely one approach. However, in my experience, Application.DoEvents is most always a hack and rarely a good idea.
My first thought, is perhaps you can create a background thread which generates your images. Begin your thread and show your modal dialog. For your thread, after it's created a certain amount (e.g. 5, 10, 20, 50, whatever), it would Invoke to the event dispatcher and execute a method which updates the ListView with the new batch of Images. Because it was only invoking periodically it would give the Modal Dialog time to process messages of its own. The function which you invoke on the event dispatcher would receive a list of images, Call ListView.BeginUpdate(), Loop through the list and create and add items, then call ListView.EndUpdate()
There's other ways you can do this, but I would really try to avoid Application.DoEvents() (which in my experience is a hack coming from Visual Basic programmers who did not understand threading).
精彩评论