This new article presents a guide to running C# Azure functions in an isolated worker process.
They comes also with:
For complete examples, see the .NET 6 isolated sample project and the .NET Framework 4.8 isolated sample project
Isolated worker processes are designed to run untrusted code in a sandboxed environment, which makes them a good choice for running code that may be potentially dangerous or untrusted. They provide a secure and efficient way to run code in isolation from the main application process.
Isolated worker processes are a feature of .NET 5 and later versions, and they can be used in any environment that supports .NET 5 or later.
Let’s see one example, with a simple create console project:
1 2 | dotnet new console dotnet add package Microsoft.Extensions.Hosting |
Change the Program.cs source code with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading; using System.Threading.Tasks; class Program { static void Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration(config => { config.AddCommandLine(args); }) .ConfigureServices((hostContext, services) => { services.AddHostedService(); }) .UseEnvironment(Environments.Production) .UseContentRoot(AppContext.BaseDirectory); var host = builder.Build(); host.Run(); } } class MyWorker : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine("Starting work..."); // Start some work... return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("Stopping work..."); // Stop the work... return Task.CompletedTask; } } |
Let’s build and run it and stop it with keys Ctrl + C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | dotnet build MSBuild version 17.4.1+fedecea9d for .NET Determining projects to restore... All projects are up-to-date for restore. ... Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:02.27 ... dotnet run Starting work... Stopping work... |