Search code examples
c#multithreadingformstreeviewdelay

C# Forms: How to show a form when initalization takes a long time?


I have a c# form, and the initialization time takes a while (its getting information from a server, and populating a TreeView). Right now, the code looks similar to this:

public class myForm : Form
{
    InitializeComponent();
    List<Location> locations = getServerLocations(); // Server call

    foreach( Location loc in locations )
    {
        List<POI> POIs = loc.getLocationPOIs(); // Server call
        foreach( POI poi in POIs ) 
        {
             List<POIDetails> = poi.getPOIDetails(); // Server call
             ....
        }
    }
}

you get the point I think ... So there is a large tree, and I know I can not make the calls all the way down until the user expands the tree. But the intent is I just want the Form to display, with a 'loading...' or something on a tool strip while all the processing and server gets are happening.

Right now, it seems as if I haven't loaded the application yet because nothing will show to the user until all the calls are complete.


Solution

  • You shouldn't do any long running processing on the UI thread - instead move this to another thread i.e using a BackgroundWorker. You can initially show the "Loading" screen and, once the background worker completes, update your UI with your tree structure.