Created
October 25, 2015 04:52
-
-
Save emoacht/aa1f919a0dc6b6906d41 to your computer and use it in GitHub Desktop.
Sample of Task.Factory.FromAsync method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good example! It can convert BeginRead/EndRead to async/await.