When a non-UI thread of WPF accesses network resources, the page is suspended.
A project in the company uses WPF as a GUI to access web interfaces to obtain data,
However, because the data volume is large and no paging is performed, a loading control is required. I checked a lot of information on the Internet but it is relatively shallow. After completing the requirements, let's summarize them.
First. The implementation of the loading control is basically 1. control display; 2. Background access query; 3. UI rendering; 4. Control hiding.
To implement this part, asynchronous operations are required. The BackgroundWorker component is used to execute time-consuming asynchronous operations such as database transactions and file downloads.
There are no too many records about backgroundWorker. Many people have classified the usage of the system. Here we only use the following methods:
1. BackgroundWorker bgMeet = new BackgroundWorker (); // create an object
2. bgMeet. workerReportsProgress = true; // to display the execution progress of background operations, you can use the corresponding ReportProgress () method to pass the progress value of the operation, this method triggers the ProgressChanged event. In this event, parameters passed by the main thread are received through the ProgressChangedEventArgs instance.
3. bgMeet. DoWork + = new DoWorkEventHandler (bgMeet_DoWork); // what needs to be done in the background
4. bgMeet. RunWorkerCompleted + = new RunWorkerCompletedEventHandler (bgMeet_RunWorkerCompleted); // feedback after completion
The following is the dowork method:
1. loading Control display
This. Dispatcher. Invoke (DispatcherPriority. Background, new Action () =>
{
This. loading. Visibility = Visibility. Visible;
}); // The dispatcher. invoke must be used here because WPF explicitly stipulates that the UI element can only be operated by its main thread.
2. getData () from the interface; // The access interface cannot use dispatcher. otherwise, the page will be suspended due to the long time when the sub-thread accesses the page.
3. Rendering data
The following is the completed method: Hide the loading control.
Void bgMeet_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)
{
This. Dispatcher. Invoke (DispatcherPriority. Background, new Action () =>
{
This. loading. Visibility = Visibility. Collapsed;
}));
}