Home > Development > APM and TPL – Reading Files

APM and TPL – Reading Files


using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace APMExamples
{
    class Program
    {
        static void Main()
        {
            Program p = new Program();
            p.ReadFileContentsAsyncAndUseAContinuationToPrintResults();

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();

        }

        public void ReadFileContentsAsyncAndUseAContinuationToPrintResults()
        {
            var stream = new FileStream(@"C:\Projects\TPLSamples\TPLSamples.sln", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 8 * 1024, FileOptions.Asynchronous);
            byte[] data = new byte[stream.Length];

            var t = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, data, 0, data.Length, null);
            t.ContinueWith(x =>
                               {
                                   Console.WriteLine(Encoding.ASCII.GetString(data));
                                   stream.Close();
                               });
        }
    }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: