-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Closed
Description
If i try to register two or more services, only one could work properly.
For example:
services.AddSingleton<IHostedService, ServiceA>();
services.AddSingleton<IHostedService, ServiceB>();
Implementations are simplest as possible:
public class ServiceA: IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
DoWork();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void DoWork()
{
while (true)
{
Console.WriteLine("ServiceA");
Thread.Sleep(2000);
}
}
}
and
public class ServiceB: IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
DoWork();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void DoWork()
{
while (true)
{
Console.WriteLine("ServiceB");
Thread.Sleep(1000);
}
}
}
In output getting messages only from ServiceA
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: d49a03c0-a844-26eb-48a5-33a612dd3ead
- Version Independent ID: 0707865f-9db7-0d71-42a5-bc1a1e89680a
- Content: Implement background tasks in microservices with IHostedService and the BackgroundService class
- Content Source: docs/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice.md
- Product: dotnet
- Technology: dotnet-ebooks
- GitHub Login: @nishanil
- Microsoft Alias: nanil