. Net4.5 new function: asynchronous file I/O

Source: Internet
Author: User

Asynchronous operations can execute a large number of resource-consuming I/O operations without stopping the main thread. Important performance considerations. The time-consuming stream operations of Windows Metro style app or desktop app will block the UI thread andProgramThe position displayed, just as it does not work.

Starting from. NET Framework 4.5 RC, the I/O type includes asynchronous methods to simplify asynchronous operations. async in its name, such as readasync , writeasync , copytoasync , flushasync , readlineasync , and readtoendasync . "> the asynchronous method name contains async , for example, readasync , writeasync , copytoasync , and fl Ushasync , readlineasync , and readtoendasync . stream , filestream , and memorystream , and on classes That are used for reading from or writing to streams, such textreader and textwriter . "> these asynchronous methods for streaming, for example, stream , filestream , memorystream , and stream reading or writing (for example, textreader and textwriter .

beginread and class = "mtpstagouterhtml"> endread to Implement Asynchronous I/O operations. "> in. in net framework 4 and earlier versions, methods such beginread and endread Implement Asynchronous I/O operations. these methods can be found in. net Framework 4.5 RC supports earlier versions of Code . However, asynchronous methods help you implement asynchronous I/O operations more easily.

starting from Visual Studio 2012 RC, Visual Studio provides two keywords for asynchronous programming:

    • async (Visual Basic) or async (C #) modifier, which is used to mark a method that contains an asynchronous operation. "> async (Visual Basic) or (C #) async modifier, used to indicate that the scheme contains an asynchronous operation.

    • await (Visual Basic) or await (C #) operator, which is applied to the result of an async method. "> await (Visual Basic) or (C #) await operator, which is applied to asynchronous Methods.

as shown in the following example, to implement asynchronous I/O operations, use these keywords in combination with the Asynchronous Method ,. asynchronous programming with async and await (C # and Visual Basic) . "> For more information, see asynchronous programming and waiting (C # and Visual Basic) .

The following example shows how to use the twoFilestreamObjects are asynchronously transferred from one directory to another. Note:ButtonControlClickEvent Handler flagAsyncModifier because it calls an Asynchronous Method.

 

Using  System;  Using  System. Threading. tasks;  Using  System. windows;  Using  System. IO;  Namespace  Wpfapplication {  Public   Partial   Class  Mainwindow: window {  Public Mainwindow () {initializecomponent ();}  Private Async Void Button_click ( Object  Sender, routedeventargs e ){  String Startdirectory = @"  C: \ Users \ exampleuser \ Start  "  ;  String Enddirectory = @"  C: \ Users \ exampleuser \ end "  ;  Foreach ( String Filename In  Directory. enumeratefiles (startdirectory )){  Using (Filestream sourcestream = File. Open (filename, filemode. Open )){  Using (Filestream destinationstream = file. Create (enddirectory + filename. substring (filename. lastindexof ( '  \\  ' ) {Await sourcestream. copytoasync (destinationstream );}}}}}} 

 

The next example is similar to the previous one,StreamreaderAndStreamwriterThe content of the object to read and write text files is asynchronous.

 

 Private Async Void Button_click (Object  Sender, routedeventargs e ){  String Userdirectory = @"  C: \ Users \ exampleuser \  "  ;  Using (Streamreader sourcereader = file. opentext (userdirectory + "  Bigfile.txt  "  )){  Using (Streamwriter destinationwriter = file. createtext (userdirectory +"  Copiedfile.txt  "  ) {Await copyfilesasync (sourcereader, destinationwriter );}}}  Public  Async task copyfilesasync (streamreader source, streamwriter destination ){  Char [] Buffer = New   Char [ Zero X 1000  ];  Int  Numread;  While (Numread = await source. readasync (buffer, 0 , Buffer. Length ))! = 0  ) {Await destination. writeasync (buffer,  0  , Numread );}} 

 

UseStreamreaderClass. The next example shows how to open a file named Metro style app.StreamAfter hiding the file and the XAML file and reading its content. It uses an Asynchronous Method to open a file to stream and read its content.

 

                      Using  System;  Using System. IO;  Using  System. text;  Using  Windows. Storage. pickers;  Using  Windows. storage;  Using  Windows. UI. XAML;  Using  Windows. UI. XAML. controls;  Namespace  Exampleapplication {publicsealedpartialclass blankpage: Page {  Public Blankpage (){  This  . Initializecomponent ();} privateasyncvoid button_click_1 (  Object  Sender, routedeventargs e) {stringbuilder Contents = New  Stringbuilder ();  String  Nextline;  Int Linecounter = 1  ;  VaR Openpicker = New  Fileopenpicker (); openpicker. suggestedstartlocation = Pickerlocationid. documentslibrary; openpicker. filetypefilter. Add (  "  . Txt  "  ); Storagefile selectedfile = Await openpicker. picksinglefileasync ();  Using (Streamreader reader = New  Streamreader (await selectedfile. openstreamforreadasync ())){ While (Nextline = await reader. readlineasync ())! = Null  ) {Contents. appendformat (  "  {0 }.  "  , Linecounter); contents. append (nextline); contents. appendline (); linecounter ++ ;  If (Linecounter> 3  ) {Contents. appendline ( "  Only first 3 lines shown.  "  );  Break  ; }}} Displaycontentsblock. Text = Contents. tostring ();}}} 

 

 

 

 

 

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.