转 Using Async for File Access
原文: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;
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.
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();
}
}
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的更多相关文章
- file access , argc, argv[ ]
_____main函数含有 两个参数 ,argc ,argv[] 这两个参数用以指示命令行输入的参数信息. argc 的值是输入的参数的数量.argv是一个数组,每个数组元素指向一个string字符串 ...
- 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 ...
- 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- ...
- 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 ...
- 编程概念--使用async和await的异步编程
Asynchronous Programming with Async and Await You can avoid performance bottlenecks and enhance the ...
- 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 ...
- C# Async, Await and using statements
Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力.比如: Application area Support ...
- Linux File System Change Monitoring Technology、Notifier Technology
catalog . 为什么要监控文件系统 : hotplug . udev . fanotify(fscking all notification system) . inotify . code e ...
- async源码学习 - 全部源码
因为工作需要,可能我离前端走远了,偏node方向了.所以异步编程的需求很多,于是乎,不得不带着学习async了. 我有个习惯,用别人的东西之前,喜欢稍微搞明白点,so就带着看看其源码. github: ...
随机推荐
- Pandas系列(十)-转换连接详解
目录 1. 拼接 1.1 append 1.2 concat 2. 关联 2.1 merge 2.2 join 数据准备 # 导入相关库 import numpy as np import panda ...
- C#连接和操作Oracle数据
最近业务需要读取远程Oracle数据库的数据,这里简单记录一下. 这里采用的是Oracle.ManagedDataAccess方式连接Oracle数据库,这种方式有几个优点:①不用安装Oracle客户 ...
- fedora make: gcc:命令未找到(解决方法)
安装C开发环境 由于gcc包需要依赖binutils和cpp包,另外make包也是在编译中常用的,所以一共需要9个包来完成安装,因此我们只需要执行9条指令即可: yum install cpp yum ...
- [再寄小读者之数学篇](2014-06-22 求极限 [中国科学技术大学2011年高等数学B考研试题])
设数列 $\sed{x_n}$ 满足 $0<x_1<\pi$, $x_{n+1}=\sin x_n\ (n=1,2,\cdots)$. (1) 证明 $\dps{\vlm{n}x_n}$ ...
- 【webpack】中mini-css-extract-plugin使用方法
这个参加可以压缩CSS,然后让CSS输出到指定的目录中 使用这个loader也很简单,只有将style-loader 替换成 MiniCssExtractPlugin.loader, 'css-loa ...
- 二进制中连续k个1-题解
原题传送门[>XJOI<] 重要提示:您的等级必须达到三级五段,否则会被一只小猫痛扁 题目描述: 求最小的m,使得m>=n而且m的二进制表示包含至少连续k个1 输入格式: 输入 ...
- 记事本 HTML
又学了一遍HTML,感觉轻松了好多,个人感觉HTML和画画差不多,只要有了想法,画出来其实并不难. 头部信息<head> 头部信息并不是给我们看的,而是给浏览器看的,当浏览器看到之后,才好 ...
- SQL Server Change Tracking
1 概述 “更改跟踪”和“变更数据捕获”捕获和记录用户表的DML更改(插入.更新和删除操作),为某些有特殊需求的应用程序服务. 1.1 更改跟踪 更改跟踪捕获表的数据行更改这一行为,但不会捕获更改的具 ...
- OpenCV3编程入门读书笔记5-边缘检测
一.边缘检测的一般步骤 1.滤波 边缘检测的算法主要是基于图像强度的一阶和二阶导数,但导数通常对噪声很敏感,因此必须采用滤波器来改善与噪声有关的边缘检测器的性能. 2.增强 增强边缘的基础是确定图像各 ...
- windows :config windows update … 一直处于假死状态
参考文章:http://www.cnblogs.com/teacat/p/9204225.html 环境:win7 64bit 旗舰版 问题:重启后,系统更新到35%后,一直处于假死状态,未能正确进入 ...