Here is a description of 2 ways to write files asynchronously:
1) Asynchronous programming model API to task--using Task.Factory.FromAsync method
2) for StreamWriter use WriteAsync method
Remember to use the fileoptions.asynchronous option with the Stream object.
First look at the preparation function:
Createfilecontent is used to randomly generate content to be written (in string form);
Sumfilecontent
static string Createfilecontent ()
{
var sb = new StringBuilder ();
for (int i = 0; i < 100000 i++)
{
sb. AppendFormat (' {0} ', new Random (i). Next (0, 99999));
Sb. Appendline ();
}
Return SB. ToString ();
}
Async static task<long> sumfilecontent (string filename)
{
using (var stream = new FileStream (fileName), FileMode.Open, Fileaccess.read,fileshare.none, Buffer_size, fileoptions.asynchronous)
using (var sr = new StreamReader (stream))
{
long sum = 0;
while (Sr. Peek () >-1)
{
string line = Await Sr. Readlineasync ();
sum = long. Parse (line);
return sum;
}
Static Task Simulateasynchronousdelete (string filename)
{return
Task.run (() => file.delete (fileName));
}
1) Task.Factory.FromAsync method
using (var stream = new FileStream ("Test2.txt", FileMode.Create, FileAccess.ReadWrite, Fileshare.none, Buffer_size, fileoptions.asynchronous))
{
Console.WriteLine ("2"). Uses I/o Threads: {0} ", stream. IsAsync);
byte[] buffer = Encoding.UTF8.GetBytes (Createfilecontent ());
var writetask = Task.Factory.FromAsync (stream. BeginWrite, Stream. EndWrite, buffer, 0, buffer. Length, null);
await writetask;
}
2) Streamwriter.writeasync method
using (var stream = file.create ("Test3.txt", Buffer_size, fileoptions.asynchronous)
using (var sw = new StreamWriter (stream))
{
Console.WriteLine ("3"). Uses I/o Threads: {0} ", stream. IsAsync);
await SW. WriteAsync (Createfilecontent ());
}
Second, read the content asynchronously from the file (four task to number, Whenall add)
Console.WriteLine ("Starting parsing files in parallel");
task<long>[] Readtasks = new task<long>[4];
for (int i = 0; i < 4; i++)
{
Readtasks[i] = sumfilecontent (string. Format ("Test{0}.txt", I + 1));
}
Long[] sums = await task.whenall (readtasks);
Console.WriteLine ("Sum in all files: {0}", sums.) Sum ());
Third, simulate asynchronous deletion (because there is no asynchronous deletion in the API)
Console.WriteLine ("Deleting Files ...");
task[] Deletetasks = new Task[4];
for (int i = 0; i < 4; i++)
{
string fileName = string. Format ("Test{0}.txt", i + 1);
Deletetasks[i] = Simulateasynchronousdelete (fileName);
}
Await Task.whenall (deletetasks);
Console.WriteLine ("Deleting complete.");