原文:https://msdn.microsoft.com/en-us/library/jj155757.aspx

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
Writing Text

The following example writes text to a file. At each await statement, the method immediately exits. When the file I/O is complete, the method resumes at the statement that follows the await statement. Note that the async modifier is in the definition of methods that use the await statement.

public async void ProcessWrite()
{
string filePath = @"temp2.txt";
string text = "Hello World\r\n"; await WriteTextAsync(filePath, text);
} private async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text); using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: , useAsync: true))
{
await sourceStream.WriteAsync(encodedText, , encodedText.Length);
};
}

The original example has the statement await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);, which is a contraction of the following two statements:

Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
await theTask;

The first statement returns a task and causes file processing to start. The second statement with the await causes the method to immediately exit and return a different task. When the file processing later completes, execution returns to the statement that follows the await. For more information, see Control Flow in Async Programs (C# and Visual Basic) and Walkthrough: Using the Debugger with Async Methods.

Reading Text

The following example reads text from a file. The text is buffered and, in this case, placed into a StringBuilder. Unlike in the previous example, the evaluation of the await produces a value. The ReadAsync method returns a Task<Int32>, so the evaluation of the await produces an Int32 value (numRead) after the operation completes. For more information, see Async Return Types (C# and Visual Basic).

public async void ProcessRead()
{
string filePath = @"temp2.txt"; if (File.Exists(filePath) == false)
{
Debug.WriteLine("file not found: " + filePath);
}
else
{
try
{
string text = await ReadTextAsync(filePath);
Debug.WriteLine(text);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
} private async Task<string> ReadTextAsync(string filePath)
{
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: , useAsync: true))
{
StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, , buffer.Length)) != )
{
string text = Encoding.Unicode.GetString(buffer, , numRead);
sb.Append(text);
} return sb.ToString();
}
}
 
Parallel Asynchronous I/O

The following example demonstrates parallel processing by writing 10 text files. For each file, the WriteAsync method returns a task that is then added to a list of tasks. The await Task.WhenAll(tasks); statement exits the method and resumes within the method when file processing is complete for all of the tasks.

The example closes all FileStream instances in a finally block after the tasks are complete. If each FileStream was instead created in a using statement, the FileStream might be disposed of before the task was complete.

Note that any performance boost is almost entirely from the parallel processing and not the asynchronous processing. The advantages of asynchrony are that it doesn’t tie up multiple threads, and that it doesn’t tie up the user interface thread.

public async void ProcessWriteMult()
{
string folder = @"tempfolder\";
List<Task> tasks = new List<Task>();
List<FileStream> sourceStreams = new List<FileStream>(); try
{
for (int index = ; index <= ; index++)
{
string text = "In file " + index.ToString() + "\r\n"; string fileName = "thefile" + index.ToString("") + ".txt";
string filePath = folder + fileName; byte[] encodedText = Encoding.Unicode.GetBytes(text); FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: , useAsync: true); Task theTask = sourceStream.WriteAsync(encodedText, , encodedText.Length);
sourceStreams.Add(sourceStream); tasks.Add(theTask);
} await Task.WhenAll(tasks);
} finally
{
foreach (FileStream sourceStream in sourceStreams)
{
sourceStream.Close();
}
}
}

When using the WriteAsync and ReadAsync methods, you can specify a CancellationToken, which you can use to cancel the operation mid-stream. For more information, see Fine-Tuning Your Async Application (C# and Visual Basic) and Cancellation in Managed Threads.

转 Using Async for File Access的更多相关文章

  1. file access , argc, argv[ ]

    _____main函数含有 两个参数 ,argc ,argv[] 这两个参数用以指示命令行输入的参数信息. argc 的值是输入的参数的数量.argv是一个数组,每个数组元素指向一个string字符串 ...

  2. Method and system for implementing mandatory file access control in native discretionary access control environments

    A method is provided for implementing a mandatory access control model in operating systems which na ...

  3. Unable to copy file, Access to the path is denied

    Unable to copy file, Access to the path is denied http://stackoverflow.com/questions/7130136/unable- ...

  4. Samba set of user authentication and file access rights

    This series is compatible with Linux certification exam LPIC. A typical Linux user-level topics omit ...

  5. 编程概念--使用async和await的异步编程

    Asynchronous Programming with Async and Await You can avoid performance bottlenecks and enhance the ...

  6. C#的多线程——使用async和await来完成异步编程(Asynchronous Programming with async and await)

    https://msdn.microsoft.com/zh-cn/library/mt674882.aspx 侵删 更新于:2015年6月20日 欲获得最新的Visual Studio 2017 RC ...

  7. C# Async, Await and using statements

    Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area           Support ...

  8. Linux File System Change Monitoring Technology、Notifier Technology

    catalog . 为什么要监控文件系统 : hotplug . udev . fanotify(fscking all notification system) . inotify . code e ...

  9. async源码学习 - 全部源码

    因为工作需要,可能我离前端走远了,偏node方向了.所以异步编程的需求很多,于是乎,不得不带着学习async了. 我有个习惯,用别人的东西之前,喜欢稍微搞明白点,so就带着看看其源码. github: ...

随机推荐

  1. go 闭包程序解读

    package main import "fmt" // 下面这函数就是闭包函数(就是返回一个匿名函数的地址的函数,其中要1.定义一个需要保护的局部变量i 2.一个匿名的函数) , ...

  2. [物理学与PDEs]第4章第3节 一维反应流体力学方程组 3.2 一维反应流体力学方程组的 Lagrange 形式

    1.  一维粘性热传导反应流体力学方程组的 Lagrange 形式 $$\beex \bea \cfrac{\p \tau}{\p t'}-\cfrac{\p u}{\p m}&=0,\\ \ ...

  3. jQuery提示组件toastr(取代alert)

    给大家推荐一款jquery提示插件:toastr 它是一个可以取代alert的提示信息框,它在PC,移动设备上都有不错的UI效果. 具体使用方法如下: 1.首先在网页头站调用他需要的js和css文件. ...

  4. 常见的cmake工程做法

    第一步,创建一个build目录存放cmake生成的中间文件: mkdir build 第二步,进入到build文件目录: cd build 第三步,cmake把代码文件生成一个makefile文件: ...

  5. pc版qq登录及移动版qq登录的申请过程

    1.在哪里接入?    网站接入QQ登录在QQ互联(https://connect.qq.com)上创建:移动应用也可以在QQ互联(https://connect.qq.com)上创建,但是不推荐如此 ...

  6. 调试 - Chrome调试

    调试 - Chrome调试 打开开发人员工具 Ctrl+Shift+i可以打开开发人员工具. 功能面板 NetWork功能面板 在当前页面打开调试工具,刷新页面后点击NetWork可以查看当前页面的H ...

  7. Nginx location 正则篇

    location 前缀 没有前缀               匹配以指定模式开头的location =                          精准匹配,不是以指定模式开头 ~       ...

  8. [转]Ubuntu中apt与apt-get命令的区别

    转载于https://www.sysgeek.cn/apt-vs-apt-get/ Ubuntu 16.04 发布时,一个引人注目的新特性便是 apt 命令的引入.其实早在 2014 年,apt 命令 ...

  9. POJ1321 棋盘问题(简单搜索)

    题意: 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放 ...

  10. canvas图片与img图片的相互转换

    最近在一个项目中,遇到了一个问题,需要把生成的canvas形式的二维码转换为图片,可以长按识别,保存等.查找了一些资料归纳总结了一些知识. 默认在jq库里进行,引入jquery.qrcode.min. ...