'Visual Studio C#/csc writes .dll output file more than once when building

I'm making an application that reloads a .dll whenever the file is written. That way when I build I auto-load the changes.

I'm using FileSystemWatcher like this (simplified):

        const string DllDir = @"C:\blah\bin\Debug\net6.0";
        const string DllFile = "dependency.dll";

        static void Main(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();
            using var watcher = new FileSystemWatcher(DllDir, DllFile);
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Changed += (a, b) =>
            {
                stopwatch.Stop();
                Console.WriteLine("Changed " + stopwatch.Elapsed);
                stopwatch.Restart();
            };
            watcher.EnableRaisingEvents = true;
            while (true) ;
        }

but whenever I build the dependency.dll project, right-clicking from the IDE Solution Explorer or calling csc directly (csc /target:library C:\blah\Example.cs /out:C:\blah\bin\Debug\net6.0\dependency.dll), I get an output like this from the watcher program:

Changed 00:00:14.6056924
Changed 00:00:00.0000761

First the 14 second delay since I started the watcher program until the dll changed, and then 76 microseconds later it has changed again! I'm using Visual Studio 2022.

I have searched but still have absolutely no clue what's going on.

Can anybody explain me what's going on? Is there a command line argument or some project configuration to avoid this? I'm trying to get to build as fast as possible, so I want to understand which unnecessary step is doing this to disable it. Otherwise I think I can just copy the dll to another path on a post-build step, but would want to understand what the compiler is doing anyway.

Thank you



Solution 1:[1]

Apparently this has to do with the file watching not the build process. Adding a copy to the post-build step showed the same behavior on the destination path.

NotifyFilters documentation says:

LastWrite: The date the file or folder last had anything written to it.

But the OnChanged doc further expands on that:

OnChanged is called when changes are made to the size, system attributes, last write time, last access time, or security permissions of a file or directory

So probably there are multiple changes being made for a single build or copy.

Thanks to https://stackoverflow.com/a/60088655/10060021

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 2bam