Slow loading forms
I am writing a C # .NET application. I am using WinForms. so I have some forms that load very slowly, especially due to the fact that they are pulling some data from some XML files and displaying it in the ListBox controls.
What I am asking is: how can I speed up the loading of forms. or how can I show an image of a spinning wheel (the one you usually see while waiting for the action to be completed by the software).
Thanks.
a source to share
Have a look at the BackgroundWorker class , which allows you to run a task on a background thread (in your case, read the XML file) and invoke a form callback when the task is complete. This allows the UI thread to freely perform useful actions (register an undo click) or show loading graphics.
The background worker also supports the ability to execute a progress callback so that your UI can inform the user about how long they need to wait.
A quick Google search pops up in this article , which seems to cover the basics.
a source to share
To show a spinning wheel, if you are using System.Windows.Forms
, take a look at the Cursor class.
For example, I created a class like this:
class WaitCursor : IDisposable
{
Cursor m_previous;
internal WaitCursor()
{
m_previous = Cursor.Current;
Cursor.Current = Cursors.WaitCursor;
}
#region IDisposable Members
public void Dispose()
{
Cursor.Current = m_previous;
}
#endregion
}
which I am using like this:
using (WaitCursor waitCursor = new WaitCursor())
{
//... any statements here, which take a long time ...
}
a source to share
- Put long code in the BackgroundWorker to offload work to a separate thread and keep the interface responsive.
- Calling BackgroundWorker from Shown event (not constructor).
- You don't have to handle the BackgroundWorker ProgressChanged event to update the UI as data loads.
- Set UseWaitCursor = true and Enabled = false after the BackgroundWorker starts and return them to the Complete event from BackgroundWorker.
a source to share
Alternatively, you can just change the cursor to a wait cursor at the beginning of init and revert to the standard at the end so that the user knows something is happening, but it's better to use threads so that (main form?) Doesn't block. Nothing says "I'm frozen" like a locked home screen. If it's the main form, maybe a splash screen that says "Loading ..." or something like that.
a source to share