. 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 the windows Metro style app or desktop app will block the UI thread and display the position of your application, just as it does not work.
Starting from. NET Framework 4.5 RC, the I/O type includes asynchronous methods to simplify asynchronous operations. Asynchronous methods include Async in their names, such as ReadAsync, WriteAsync, CopyToAsync, FlushAsync, ReadLineAsync, and ReadToEndAsync. These Asynchronous Method convection classes, such as Stream, FileStream, and MemoryStream, and classes used for reading or writing to a Stream (such as TextReader and TextWriter.
In. NET framework 4 and earlier versions, you must use methods like BeginRead and EndRead to Implement Asynchronous I/O operations. These methods support the old version of code in. NET Framework 4.5 RC. 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 (c #) async modifier, used to indicate that the scheme contains an asynchronous operation.
• The Await (Visual Basic) or (c #) await operator applies to the results of asynchronous methods.
As shown in the following example, to implement asynchronous I/O operations, use these keywords in combination with the Asynchronous Method ,. For more information, see asynchronous programming and asynchronous and wait (C # and Visual Basic ).
The following example shows how to use the two FileStream objects of the copied file to asynchronously transition from one directory to another. Note that the Click event handler of the Button control marks the async modifier because it calls the 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, but uses StreamReader and StreamWriter objects to read and write text files asynchronously.
 
 
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 [0x1000];
Int numRead;
While (numRead = await Source. ReadAsync (buffer, 0, buffer. Length ))! = 0)
{
Await Destination. WriteAsync (buffer, 0, numRead );
}
}
 
 
Use the StreamReader class instance. The next example shows how to open the code hidden file and XAML file of Stream whose file is Metro style app, and then read 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 ();
}
}
}
 

 


From love007

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.