Getting Started with UWP development (21)-Keeping the UI thread in a responsive state

Source: Internet
Author: User

GUI programs can sometimes be completed by waiting for a time-consuming operation, causing the interface to die. This article discusses how to optimize processing in the context of what we might encounter in UWP development.

Assuming there is currently a click button Jump page operation, the new page opened by the button, there are some time-consuming actions during initialization.

         Public voidOnnavigatedto (Objectobj) {            varWatch =NewStopwatch (); Debug.WriteLine ("---------------Start"); Watch.            Start (); //assuming it takes 1 secondsdobusywork (); //Takes 1 seconds            intCount =Getpersoncount (); //Suppose that it takes 500 milliseconds to create a person each timePersonlist =createpersonlist (count); Watch.            Stop (); Debug.WriteLine (watch.            Elapsedmilliseconds); Debug.WriteLine ("----------------Stop"); Notify="page initialization is complete! Timings:"+ Watch. Elapsedmilliseconds +"milliseconds"; }

It can be noted that the above methods are sequential synchronous execution, after clicking the Jump button, there will be a noticeable deadlock and very awkward waiting process. The Getpersoncount method returns the number, the StopWatch Record will take about 7 seconds, after 7 seconds to open the jump page, This is an intolerable time.

The primary idea of optimization is to place operations that do not need to wait for completion into non- UI threads. It is found here that the method of dobusywork can be peeled off.

Task.run (() = {dobusywork ();});

After writing it found that although the reduction of 1 seconds, but the meaning is not big, still very card. The personlist assignment must be performed on the UI thread, not enough to put the Task into the background, and the optimization of this step seems to be out of the picture.

the next idea is to use async and await the keyword to do asynchronous programming, first of all we have to explicitly use the await statement is still blocking and waiting to complete before the next sentence can be executed. The difference is that the program Yeid return at the time of the await so that the UI thread remains responsive. but incorrect or inappropriate use of await Often leads to unexpected results, even worse performance than synchronous execution. Let's look at the first version of the async program:

         Public Async voidOnnavigatedto (Objectobj) {            varWatch =NewStopwatch (); Debug.WriteLine ("---------------Start"); Watch.            Start (); //Unnecessary wait, 1 seconds            awaitDobusyworkasync (); //Takes 1 seconds to return the number            intCount =awaitGetpersoncountasync (); //get methods that still cause long-time blockingPersonlist =awaitCreatepersonlistasync (count); Watch.            Stop (); Debug.WriteLine (watch.            Elapsedmilliseconds); Debug.WriteLine ("----------------Stop"); Notify="page initialization is complete! Timings:"+ Watch. Elapsedmilliseconds +"milliseconds"; }

Run Discovery,NavigateTo the second page soon (this isawaitpersonlist fully loaded, Still time consuming 7 seconds. The first mistake here is unnecessary await dobusyworkasync This method should be decisively removed await keyword, although visual studiowarning: " because this call does not wait, Therefore, the current method will continue until this call is complete. Consider applying the dobusyworkasync The return value of the method is determined by the taskvoid

        Private Async void Dobusyworkasync ()        {            await task.delay (+);        }

You may not have stack information when you catch an exception after you change to void, so you don't have to worry about this as a simple method.

The Createpersonlistasync method relies on The return value of the Getpersoncountasync, which is not a good optimization scenario. Can only say getpersoncountasync of this one second you are worth waiting for.

As for the Createpersonlistasync method itself takes 5 seconds to become a performance bottleneck, the method is analyzed:

 private  async  task< Observablecollection<person>> Createpersonlistasync (int   count) { var  list = new observablecollection<person> ();  for  (int  i = 0 ; I < count; I++ var  person = await   Person.createpresonasync (i, i.tostring ()); List.            ADD (person);         return   list; }

for loop, each time await Person.createpresonasync have 500 milliseconds waiting to happen. In fact, each create preson

 private  observablecollection<person>            Createpersonlistwithcontinue (int   count) {  var  list = new             Observablecollection<person> ();  for  (int  i = 0 ; I < count; I++ => list. Add (_.            Result), Taskscheduler.fromcurrentsynchronizationcontext ());         return   list; }

Modified to run the effect is very good, the first page between the jump no longer lag, while the load time of the personlist has also been significantly shortened, in the " page initialization has been completed " This sentence appears shortly after the list is loaded complete, But careful observation reveals that the order of the elements is disordered.

  

This is because the createpersonasync operation in the for loop is equivalent to concurrency, and the order added to the List is naturally not fixed. We can fix this by sorting before inserting.

        PrivateObservablecollection<person> Createpersonlistwithcontinue (intcount) {            varList =NewObservablecollection<person>();  for(inti =0; I < count; i++) {Person.createpresonasync (I, i.tostring ()). ContinueWith (_= {                    varperson = _.                    Result; intindex = list. Count (p = p.age <Person .                    Age); List.                Insert (index, person);            },taskscheduler.fromcurrentsynchronizationcontext ()); }            returnlist; }

At this point the program is calculated to have a better effect, there are two points can be summed up:

    1. Through Task. Run runs non-UI-related operations on a background thread, reducing unnecessary wait times
    2. You can keep the UI thread responsive by splitting the time-consuming operation into an asynchronous method returned by N await

GitHub:https://github.com/manupstairs/UWPSamples/tree/master/UWPSamples/KeepUIResponsive

Getting Started with UWP development (21)-Keeping the UI thread in a responsive state

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.