原文: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. Entity Framework入门教程(19)---EF中使用事务

    EF中使用事务 这节介绍EF6中事务的使用.EF core中事务的使用方式和EF6中一模一样. 1.EF中的默认的事务 默认情况下,当我们执行一个SaveChanges()方法时就会新建了一个事务,然 ...

  2. 第十节: EF的三种追踪实体状态变化方式(DBEntityEntry、ChangeTracker、Local)

    一. 简介 我们在前面章节介绍EF基本增删改的时候,曾说过EF的SaveChanges()方法,会一次性的将所有的实体的状态变化统一提交到数据库,那么你是否想过EF的实体会有哪些状态变化呢?什么原因会 ...

  3. MyEclipse 2015 Stable 2.0破解方法

    本篇博文简单介绍一下利用网上说明的方法破解MyEclipse 2015 Stable 2.0的具体细节.因为原来在贴吧上的方法不够详细,所以本人重新整理了一下.方法源自:http://tieba.ba ...

  4. SQL Server 常用的系统函数

    Ø  简介 本文主要列举 SQL Server 中常用的一些系统函数,帮助我们在编写 SQL 时忘了某个函数的用法方便查阅.主要分为以下几类函数,更多函数可参考官网. 1.   字符串函数 2.   ...

  5. SSH框架之hibernate《三》

    Hibernate03     一.多表设计         1.1多表设计的总则             问题:我们为什么要学习多表映射?             答:                ...

  6. 设计模式三: 代理模式(Proxy) -- JDK的实现方式

    简介 代理模式属于行为型模式的一种, 控制对其他对象的访问, 起到中介作用. 代理模式核心角色: 真实角色,代理角色; 按实现方式不同分为静态代理和动态代理两种; 意图 控制对其它对象的访问. 类图 ...

  7. ALU底层方法及计算机整数加减乘除模拟

    ALU是计算机CPU的核心,即 算术逻辑单元(arithmetic and logic unit)ALU有几大功能,是计算机计算最基础的功能:1.算术运算:包含加法.减法等2.逻辑运算:主要是布尔运算 ...

  8. jsp 异步处理

    一.  概述 异步处理功能可以节约容器线程.你应该将此功能 使用在长时间运行的操作上.此功能的作用是释放正在 等待完成的线程,使该线程能够被另一请求所使用. 二. 编写异步Servlet和过滤器 We ...

  9. Web.Config加密与解密

    可以使用受保护配置来加密 Web 应用程序配置文件(如 Web.config 文件)中的敏感信息(包括用户名和密码.数据库连接字符串和加密密钥).对配置信息进行加密后,即使攻击者获取了对配置文件的访问 ...

  10. 我的Python笔记

    声明:本文整理借鉴金角大王的Python之路,Day1 - Python基础1,仅供本人学习使用!!! 本节内容 Python介绍 发展史 Python 2 or 3? 安装 Hello World程 ...