Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: command line options

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?

like image 989
kamilk Avatar asked Oct 21 '22 07:10

kamilk


1 Answers

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.

like image 128
Jon Skeet Avatar answered Oct 28 '22 19:10

Jon Skeet