"C #" C # in deep async

Source: Internet
Author: User
Tags finally block

1. c#5.0 added async, await keyword. asyncis the modifier used when declaring an async method, the declaration is placed before the return value, the await expression is responsible for consuming asynchronous operations, cannot appear in a catch or finally block, a non-asynchronous anonymous function (an anonymous method that is not declared with async or a lambda expression), Used in lock statements or unsafe code.

PS: These constraints are intended to guarantee security, especially with regard to lock constraints. If you want to hold the lock when the asynchronous operation is complete, you should redesign your code. try/finallyinstead of bypassing the compiler's limitations by manually calling and in the Block Monitor.TryEnter , you Monitor.Exit should implement the code changes so that locks are no longer needed during the operation. If the code is not allowed to change at this point, consider using SemaphoreSlim and its WaitAsync methods instead.

2. All async methods that are modified with Async are not allowed to use out or ref modifiers. The return value must be void, task, task<t>. Typically a task. Because the caller is allowed to monitor the state of the asynchronous operation.

3. The main purpose of the await is to avoid blocking while waiting for the time-consuming operation to complete. The code always returns when it executes to await, and when it arrives, it verifies that the result exists if the result does not exist, it is scheduled for a follow-up operation that records the position, state, and then the code goes back to the UI main thread to continue running. At this point the Button.Click method has actually finished executing. The call stack is now the event loop for Windows Form, and the code after the await token will continue to run when the result is obtained.

Here is a demo quiz program I wrote:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSystem.Threading;7 usingSystem.Net.Http;8 usingSystem.Net;9 usingSystem.Diagnostics;Ten usingSystem.IO; One  A namespaceDennisdemos.demos - { -     classAsyncdemo the     { -          Public voidRun () -         { -             //var result = Test1 (); +             //Console.WriteLine (Result. Result);//you must wait until the result to continue executing the following code. So result is synchronous. -             //Console.WriteLine ("Test1 End"); +Console.WriteLine ("mainasync start."); A             varRESULT2 =Mainasync (); at              -Console.WriteLine ("Mainasync end."); -              while(!result2. iscompleted) -             { -Thread.Sleep ( +); -Console.WriteLine ("waiting ."); in             } -Console.WriteLine ("end."); to         } +         Static AsyncTask Mainasync () -         { thetask<string> task = Readfileasync ("Logicdocument_docaveloadbalance.docx");//? Start asynchronous Read *             Try $             {Panax NotoginsengConsole.WriteLine ("start to wait reads file Reult."); -                 stringText =awaitTask//? Wait for content theThread.Sleep (10000); +Console.WriteLine ("File Contents"); A             } the             Catch(IOException e)//? Processing IO failure +             { -Console.WriteLine ("caught IOException: {0}", e.message); $             } $         } -  -         Static Asynctask<string> Readfileasync (stringfilename) the         { -Console.WriteLine ("start to read file async.");Wuyi             using(varreader = File.OpenText (filename))//? Synchronizing open Files the             { -                 varresult =awaitReader. Readtoendasync (); WuThread.Sleep ( +); -Console.WriteLine ("get read file async result."); About                 returnresult; $             } -         } -     } -}
Asyncdemo

To be continued.

"C #" C # in deep async

Related Article

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.