Quick introduction
Visual Studio has had an edit and continue debug functionality for quite some time which sort of half works but Visual Studio 2022 introduces an improved capability which they call “hot reload” which appears to effectively patch the running executable with code changes. This functionality is also accessible (in a reduced capacity) using the dotnet command line tools.
Trying it out on the command line
For a quick example, create a new command line app using dotnet new console
.
Change program.cs
to the following code
int a = 0;
while (true)
{
Console.WriteLine(a);
Update(ref a);
Thread.Sleep(1000);
}
void Update(ref int a)
{
a++;
}
From the command line type dotnet watch
. This command builds and runs the program as well as looking for any changes to the source file.
The console will display the fact that Hot reload is enabled and start running the program.
D:\source\brian>dotnet watch
watch : Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload. Press "Ctrl + R" to restart.
watch : Building...
Determining projects to restore...
All projects are up-to-date for restore.
brian -> D:\source\brian\bin\Debug\net6.0\brian.dll
watch : Started
0
1
2
3
4
5
6
If the code that increments a is changed to a += 2
and the file saved, the following is observed in the command prompt.
watch : File changed: D:\source\brian\Program.cs.
7
8
9
watch : Hot reload of changes succeeded.
10
12
14
16
18
Debugging in Visual Studio 2022
Whilst dotnet watch
is useful, it does not allow for easy debugging of Hot reloaded code. For that, Microsoft recommend using Visual Studio 2022.
Reloading the same project in Visual Studio 2022, a new button with a fire-like icon appears on the toolbar.
Changing the code that increments the variable and pressing this new button causes the debugged executable to be patched with the new functionality. Breakpoints will continue to operate as before. The drop-down next to the button also allows Hot Reload on File Save
functionality similar to the behavior we saw with dotnet watch
.
Hot Reload in Maui Applications
Maui applications take this approach one step further and allow for hot reload of the user interface as well as the code behind. Maui workloads are still in prerelease but can be installed on a system using the command dotnet workload install maui
.
Hot Reload in the latest preview doesn’t seem to work for Maui.