dotnet / dotnet/docs

BackgroundServiceExceptionBehavior recommendation should prefer "Environment.ExitCode = 1" over "Environment.Exit(1)"

Open
#42,466 0 comments 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

### Type of issue

Other (describe below)

### Description

https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service#service-recovery-options-and-net-backgroundservice-instances explains you ought to use `Environment.Exit(1)` after catching exceptions.
The issue with that approach is, however, it:
* breaks unit tests that try to test this, as they exit early
* breaks `AppDomain.CurrentDomain` events that are supposed to happen afterwards, if registered

[This popular Stackoverflow question makes this a topic](https://stackoverflow.com/questions/73159671/error-handling-in-net-6-backgroundservices-hosted-in-a-windows-service) and [this answer here solves it](https://stackoverflow.com/a/77681034/15488899): Just use `Environment.ExitCode = 1;` (and possibly rethrow the exception!).

IMHO it should be documented as that, as this is a way better practice, or is not it?

Also IMHO, that behavior is buggy in :NET in general and should not happen like that, because in case of an exception exiting with `0` exit code is bad not only for Windows Services, but also kubernetes and all systems, basically. It's bad practise to swallow errors like this and that is what exit codes are supposed to be used for. But anyway...

### Page URL

https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service#service-recovery-options-and-net-backgroundservice-instances

### Content source URL

https://github.com/dotnet/docs/blob/main/docs/core/extensions/windows-service.md

### Document Version Independent Id

64d5cdf8-e50f-0c89-7f16-82645ba6383e

### Article author

@IEvangelist

### Metadata

* ID: ed148088-4550-2788-0756-390eab15e3f6
* Service: **dotnet-fundamentals**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.