"C #" 62. Several ways to read and write files asynchronously: Task.factory.fromasync,writeasync

Source: Internet
Author: User

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.");




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.