How To Load UI Independent Of Data
I am creating an application using c# and database in webserver.while accessing data from the webserver ,it is very slow and the form is also gets hanged up until the d开发者_如何学JAVAatas are loaded.Is there a way to load the form first and the datas later ?
The common way to solve this is to use the BackgroundWorker
class.
public void InitBackgroundWorker()
{
backgroundWorker.DoWork += YourLongRunningMethod;
backgroundWorker.RunWorkerCompleted += UpdateTheWholeUi;
backgroundWorker.WorkerSupportsCancellation = true; // optional
// these are also optional
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += UpdateProgressBar;
}
// This could be in a button click, or simply on form load
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync(); // Start doing work on background thread
}
// ...
private void YourLongRunningMethod(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
if(worker != null)
{
// Do work here...
// possibly in a loop (easier to do checks below if you do)
// Optionally check (while doing work):
if (worker.CancellationPending == true)
{
e.Cancel = true;
break; // If you were in a loop, you could break out of it here...
}
else
{
// Optionally update
worker.ReportProgress(somePercentageAsInt);
}
e.Result = resultFromCalculations; // Supports any object type...
}
}
private void UpdateProgressBar(object sender, ProgressChangedEventArgs e)
{
int percent = e.ProgressPercentage;
// Todo: Update UI
}
private void UpdateTheWholeUi(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// Todo: Update UI
}
else if (e.Error != null)
{
string errorMessage = e.Error.Message;
// Todo: Update UI
}
else
{
object result = e.Result;
// Todo: Cast the result to the correct object type,
// and update the UI
}
}
Heard of multi threading ? see this and this for examples.
If multithreading is hard for you, you can load part of that data at first, and then put some buttons on your form to let the user fetch other parts of data. This is commonly called on-demand loading and when implemented called paging. Imagine that you have 10000 records of information. You can load first 100 records, then let the user load the second 100 records only when he wants. If your doing some lengthy operations on the server and the problem is not about on-demand loading, then the only way is to use threading :)
You could fetch the data in other thread
not in the UI thread
. This way your UI doesn't get stuck. Have a look at this post explaining threading.
Remember that you can't update the controls from thread other than the thread it was created on. To resolve this, have a look at this post.
What kind of data you use?
You can use a BackgroundWorker or in some cases there are async-methods (if you call a webservivce, for example)
精彩评论