© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
10 replies
Relevant

❔ How to restart a BackgroundService

Searching the internets, I seem to be finding answers that don't really seem right, and not good even if they are right.

Is there a way to get the instance of a hosted service that may have stopped so that I can restart it?

I tried this, but service ended up being
null
null
in this case:

using (var scope = serviceScopeFactory.CreateScope())
{
    var service = scope.ServiceProvider.GetService<MyBackgroundService>();

    if (service != null)
    {
        try
        {
            await service.StopAsync(default);
            await service.StartAsync(default);
        }
        catch (Exception ex)
        {
            Log.Error(ex, ex.Message);
        }
    }

}
using (var scope = serviceScopeFactory.CreateScope())
{
    var service = scope.ServiceProvider.GetService<MyBackgroundService>();

    if (service != null)
    {
        try
        {
            await service.StopAsync(default);
            await service.StartAsync(default);
        }
        catch (Exception ex)
        {
            Log.Error(ex, ex.Message);
        }
    }

}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

BackgroundService Question
C#CC# / help
11mo ago
❔ Windows BackgroundService
C#CC# / help
3y ago
❔ Create a HostedService using BackgroundService to listen to requests
C#CC# / help
4y ago
✅ BackgroundService blocking on Startup
C#CC# / help
3mo ago