简体   繁体   中英

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

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: 命令行选项

If I open the file within those 10s when my application is still running, the file does contain "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? 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.

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. 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. 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. 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". 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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