zoukankan      html  css  js  c++  java
  • C#异步将文本内容写入文件

    在C#/.NET中,将文本内容写入文件最简单的方法是调用 File.WriteAllText() 方法,但这个方法没有异步的实现,要想用异步,只能改用有些复杂的 FileStream.WriteAsync() 方法。

    使用 FileStream.WriteAsync() 有2个需要注意的地方,1是要设置bufferSize,2是要将useAsync这个构造函数参数设置为true,示例调用代码如下:

    public async Task CommitAsync()
    {
        var bits = Encoding.UTF8.GetBytes("{"text": "test"}");
        using (var fs = new FileStream(
            path: @"C:	emp	est.json", 
            mode: FileMode.Create, 
            access: FileAccess.Write, 
            share: FileShare.None, 
            bufferSize: 4096, 
            useAsync: true))
        {
            await fs.WriteAsync(bits, 0, bits.Length);
        }
    }

    看这个方法的帮助文档中对useAsync参数的说明:

    //   useAsync:
            //     Specifies whether to use asynchronous I/O or synchronous I/O. However, note
            //     that the underlying operating system might not support asynchronous I/O,
            //     so when specifying true, the handle might be opened synchronously depending
            //     on the platform. When opened asynchronously, the System.IO.FileStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)
            //     and System.IO.FileStream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)
            //     methods perform better on large reads or writes, but they might be much slower
            //     for small reads or writes. If the application is designed to take advantage
            //     of asynchronous I/O, set the useAsync parameter to true. Using asynchronous
            //     I/O correctly can speed up applications by as much as a factor of 10, but
            //     using it without redesigning the application for asynchronous I/O can decrease
            //     performance by as much as a factor of 10.

    从中可以得知,只有设置useAsync为true,才真正使用上了异步IO。

  • 相关阅读:
    POJ 3660 Cow Contest (floyd求联通关系)
    POJ 3660 Cow Contest (最短路dijkstra)
    POJ 1860 Currency Exchange (bellman-ford判负环)
    POJ 3268 Silver Cow Party (最短路dijkstra)
    POJ 1679 The Unique MST (最小生成树)
    POJ 3026 Borg Maze (最小生成树)
    HDU 4891 The Great Pan (模拟)
    HDU 4950 Monster (水题)
    URAL 2040 Palindromes and Super Abilities 2 (回文自动机)
    URAL 2037 Richness of binary words (回文子串,找规律)
  • 原文地址:https://www.cnblogs.com/dudu/p/async_file_write_text.html
Copyright © 2011-2022 走看看