Asynchronous File I/O in .net framework 4.5

Asynchronous operations enable you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working.
Starting with the .NET Framework 4.5, the I/O types include async methods to simplify asynchronous operations. An async method contains Async in its name, such as ReadAsync, WriteAsync, CopyToAsync, FlushAsync, ReadLineAsync, and ReadToEndAsync. These async methods are implemented on stream classes, such as Stream, FileStream, and MemoryStream, and on classes that are used for reading from or writing to streams, such TextReader and TextWriter.
In the .NET Framework 4 and earlier versions, you have to use methods such as BeginRead and EndRead to implement asynchronous I/O operations. These methods are still available in the .NET Framework 4.5 to support legacy code; however, the async methods help you implement asynchronous I/O operations more easily.
Starting with Visual Studio 2012, 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.
  • Await (Visual Basic) or await (C#) operator, which is applied to the result of an async method.

To implement asynchronous I/O operations, use these keywords in conjunction with the async methods, as shown in the following examples. For more information, see Asynchronous Programming with Async and Await (C# and Visual Basic).
The following example demonstrates how to use two FileStream objects to copy files asynchronously from one directory to another. Notice that the Click event handler for the Button control is marked with the async modifier 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);
                    }
                }
            }
        }
    }
}
Tagged . Bookmark the permalink.

Leave a Reply