简体   繁体   English

Visual Studio在调试结束时清除输出文件

[英]Visual Studio clears output file at end of debugging

I am experiencing a weird behaviour from Visual Studio 2013. I've got a C# program which writes to the standard output, let's say 我在Visual Studio 2013中遇到了一个奇怪的行为。我有一个C#程序写入标准输出,让我们说

using System;
using System.Threading;

namespace CsSandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
            Thread.Sleep(10000);
        }
    }
}

In the Debug tab of the project's properties I have redirected the output to a file, like this: 在项目属性的Debug选项卡中,我已将输出重定向到文件,如下所示: 命令行选项

If I open the file within those 10s when my application is still running, the file does contain "Hello world!". 如果我在应用程序仍在运行时在这些10s内打开文件,则该文件确实包含“Hello world!”。 However, as soon as the program exits, the file is cleared. 但是,一旦程序退出,文件就会被清除。 This does not happen when I run the program from the command line. 从命令行运行程序时不会发生这种情况。

Is there a rationale why Visual Studio does it? 有没有理由为什么Visual Studio会这样做? Is there a way to bypass this behaviour? 有没有办法绕过这种行为?

I believe this is due to the way Visual Studio hosts your application, in order to reduce startup time when debugging. 我相信这是由于Visual Studio托管您的应用程序的方式,以减少调试时的启动时间。

What happens is that your application (Program.exe) will actually be hosted in another process (Program.vshost.exe), which is started with the same command line arguments. 发生的情况是您的应用程序(Program.exe)实际上将托管在另一个进程(Program.vshost.exe)中,该进程以相同的命令行参数启动。 When your application ends, this process is immediately restarted. 当您的应用程序结束时,立即重新启动此过程。 You should be able to see this within Task Manager - look in the details tab so you can see the PID of the processes, and run your app - you'll see one Program.vshost.exe instance which ends when your app finishes, and another one come up immediately. 您应该能够在任务管理器中看到这一点 - 查看详细信息选项卡,以便您可以看到进程的PID,并运行您的应用程序 - 您将看到一个Program.vshost.exe实例,该实例在您的应用程序完成时结束,并且另一个人立即上来。 That's then overwriting your output file. 然后,这将覆盖您的输出文件。

One fix for this is to give your application a command line argument for the file to write to - and open that file within your Main method. 解决此问题的一个方法是为应用程序提供要写入的文件的命令行参数 - 并在Main方法中打开该文件。 You won't get there until you start running the app again. 在您再次开始运行应用程序之前,您将无法到达那里

Another option would be to simply stop using the hosting process - in the Debug part of your project properties, at the bottom you should see a checkbox for "Enable the Visual Studio hosting process". 另一种选择是简单地停止使用托管过程 - 在项目属性的Debug部分中,在底部你应该看到一个“启用Visual Studio托管过程”的复选框。 Uncheck this and I think your problem will go away - but it'll take longer to start debugging. 取消选中此项,我认为您的问题将会消失 - 但开始调试需要更长时间。

See this blog post for more information about the hosting process. 有关托管过程的更多信息,请参阅此博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM