Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created October 25, 2015 04:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emoacht/aa1f919a0dc6b6906d41 to your computer and use it in GitHub Desktop.
Save emoacht/aa1f919a0dc6b6906d41 to your computer and use it in GitHub Desktop.
Sample of Task.Factory.FromAsync method
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
if (0 == args.Length)
return;
var result = ReadFileAsync(args[0]).Result;
Console.WriteLine(result);
Console.ReadKey();
}
static async Task<string> ReadFileAsync(string filePath)
{
if (!File.Exists(filePath))
return null;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var buff = new byte[fs.Length];
return await Task.Factory.FromAsync(fs.BeginRead, fs.EndRead, buff, 0, buff.Length, TaskCreationOptions.None)
.ContinueWith(_ =>
{
using (var ms = new MemoryStream(buff))
using (var sr = new StreamReader(ms))
return sr.ReadToEnd();
});
}
}
}
@guojianwei001
Copy link

good example! It can convert BeginRead/EndRead to async/await.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment