在我的C#代码中,计算机是否一直等到输出完成后再继续? [英] In my C# code does the computer wait until output is complete before moving on?

查看:135
本文介绍了在我的C#代码中,计算机是否一直等到输出完成后再继续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建一个名为'lotsofdata'的长字符串,然后使用以下代码输出其内容:

Let's say I make a long string called 'lotsofdata', and then output its content with this code:

        string outputFilePath = @"C:\output.txt";
        System.IO.File.WriteAllText(outputFilePath, lotsofdata);

        SpecialFunction1();
        SpecialFunction2();
        SpecialFunction3();

我的问题是,在继续前进之前,计算机是否完全将所有内容写入output.txt运行SpecialFunction1?或者,它是否将输出过程设置为运动并在输出过程完成之前移至SpecialFunction1?

My question is, does the computer completely finish writing all of the stuff to output.txt before moving on to running SpecialFunction1? Or, does it set the outputting process in motion and move on to SpecialFunction1 before the outputting process is complete?

我问,因为我想确保output.txt在继续执行SpecialFunction1()之前完成了写入,我不知道如何确保这一点。

I'm asking because I want to make sure output.txt is done being written to before proceeding to SpecialFunction1() and I don't know how to ensure this.

推荐答案

简单的答案是是。

WriteAllText 之前填充基础流并关闭(重要位)方法退出。

The underlying stream is filled and closed (the important bit) before the WriteAllText method exits.


File.WriteAllText方法

创建一个新文件,将内容写入该文件,然后关闭
该文件。如果目标文件已经存在,则会被覆盖。

Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

http://msdn.microsoft.com/en-us/library/system.io.file .writealltext%28v = vs.110%29.aspx

这不是所有文件写入的黄金法则。如果您直接写入 FileStream ,则需要确保调用 Flush 关闭(理想情况下,你应该总是调用关闭)如果你想确保在继续之前实际写入文件。

This is not a golden rule for all file writing. If you were writing directly to a FileStream, you would need to make sure you call Flush or Close (ideally, you should always call Close anyway) if you want to make sure that the file is actually written before continuing.


FileStream.Close方法

以前写入的任何数据在
文件流关闭之前,缓冲区被复制到文件中,因此在
调用Close之前不必调用Flush。在调用Close之后,对文件
流的任何操作都可能引发异常。在调用一次关闭后,如果再次调用,则
不执行任何操作。

Any data previously written to the buffer is copied to the file before the file stream is closed, so it is not necessary to call Flush before invoking Close. Following a call to Close, any operations on the file stream might raise exceptions. After Close has been called once, it does nothing if called again.

http://msdn.microsoft.com/en-us/library/aa328800%28v= vs.71%29.aspx

这里的关键点是刷新流的任何操作都不会退出直到数据被写入目的地。

The key takeaway for you here is that any operation that flushes a stream will not exit until the data has been written to its destination.

这篇关于在我的C#代码中,计算机是否一直等到输出完成后再继续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆