Let's look at the example:
1 void Pagepaint () 2 {3 Console.WriteLine ("Paint Start"), 4 paint (), 5 Console.WriteLine ("Paint End"), 6} 7< c4/>8 void Paint () 9 { Rendering ("Header"), Rendering (Requestbody ()), Rendering ("Footer"); 13}14 Page Requestbody () : {thread.sleep (+); return "Body"; 19}
Suppose there is a method for this page layout that renders the head, the body, and the bottom in turn, the header and the bottom are fixed content, and the body needs additional requests.
Here with sleep Analog network delay, rendering method is actually the simple encapsulation of Console.WriteLine ...
After the Pagepaint run, the result is this:
Paint Startheaderbodyfooterpaint End
Quite normal results, but the header rendered after the page blocked, this time the user can not operate on the header.
So the amendment is made:
1 async void Paint () 2 {3 Rendering ("Header"), 4 Rendering (await Requestbody ()), 5 Rendering ("Footer"); 6} 7 8 Async task<string> Requestbody () 9 {Ten return await Task.run (() =>11 { thread.sleep (1000 ) ( return "Body"); 15}
The result of the operation becomes this:
Paint Startheaderpaint Endbodyfooter
This will not block the main thread after the header appears.
However, footer has to wait until the body rendering is complete before it can be rendered, and this logic now looks fine because the bottom is laid out relative to the body.
However, I want to add an ad to the page at this time, and it is fixed positioning of the kind, tube what the head of the body want to cover the cover, you where it regardless.
For example, write this:
1 async void Paint () 2 {3 Rendering (await requestads ()); 4 Rendering ("Header"); 5 Rendering (await Requestbody ()); 6 Rendering ("Footer"); 7}
There is a serious problem, the head has to wait for the ads to be loaded before rendering, this is obviously wrong.
So it should be changed to this:
1 async void Paint () 2 {3 paintads (), 4 Rendering ("Header"), 5 Rendering (await Requestbody ()), 6 Rendering ("Footer"); 7} 8 9 async void Paintads () Ten {one string ads = await Task.run (() =>12 { thread.sleep ( +); return "ads"; Rendering (ADS); 17}
The result of this operation is satisfactory:
Paint Startheaderpaint Endadsbodyfooter
C # Async and await usage (blocking and non-blocking)