C# Forms: How to show a form when initalization takes a long time?
I have a c# form, and the initialization tim开发者_C百科e 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.
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.
You should work with multi threading process, so that you can separate the process that takes time from the rest of the process. Here is a blog that may help you. .NET 4.0 and System.Threading.Tasks
Running your initialization on a separate thread is the preferred way. But if you're constrained to run it on the UI thread then try calling Application.DoEvents() right after your call to .Show() or .ShowDialog() of your form.
If the form shows up, it will still be unresponsive to user actions until the initialization is completed. So running the initialization on a separate thread is the better solution.
精彩评论