Recently, there were two new features merged in .NET 10 I think are small little quality of life improvements: Avoid Blocking on startup with BackgroundServices and a new string comparer.
Avoid Blocking on startup with BackgroundService
s
The first one (link here: #36063) is a small change in the way BackgroundServices are started in .NET 10. If you have a BackgroundService in your application, you might have noticed that it blocks the application startup until the service is started. This is because the StartAsync
method is called synchronously in the IHostedService
implementation. You could do tricks like such to come around this:
public class MyBackgroundService : BackgroundService
{
private readonly IHostApplicationLifetime _appLifetime;
public MyBackgroundService(IHostApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Yield();
// Do your work here
}
}
Or wrap the whole thing in a Task.Run
. But that is not really nice and easy to discover. In .NET 10, the BackgroundService
class will now have a new virtual property called StartAsynchronously
which is set to true
by default. This means that the StartAsync
method will be called asynchronously, and the application will not block on startup. You have to explicitly set it to false
if you want the old behavior.
EDIT: BackgroundService
will not get an additional property (aka StartAsynchronously
) but the behavior will shift towards the async nature. Thanks @kapsiR for pointing that out.
New String Comparer
The second one (link here: #13979 describes the following issue, imagine you want to sort the following two strings: Windows 10 and Windows 7. Treating them purely as strings, Windows 10 would come before Windows 7 because the character 1 comes before 7. But there are contexts where you need to treat some part of the string as a number and sort it accordingly. This is where the new StringComparer
comes in. It will allow you to sort strings as numbers, so Windows 10 will come after Windows 7.
var list = new List<string> { "Windows 10", "Windows 7" };
list.Sort(StringComparer.NumericOrdering); // The API is different than in the original post!
Another example, hinted in the ticket, is sorting IP addresses.