Working with Windows Services in .NET — Complete Guide from Scratch to Production

15–22 minutes

Introduction

Enterprise Applicationsలో కొన్ని పనులు user request లేకుండానే backgroundలో నిరంతరం run అవుతూ ఉండాలి.

ఉదాహరణకు:

  • Pending Orders process చేయడం
  • Invoices generate చేయడం
  • Email/Notifications పంపించడం
  • ఒక Folderలో వచ్చే Filesను process చేయడం
  • రెండు Systems మధ్య Data Synchronization చేయడం
  • Message Queue నుంచి messages process చేయడం
  • Reports generate చేయడం
  • Application health monitor చేయడం
  • Temporary files cleanup చేయడం

ఇలాంటి పనుల కోసం ప్రతి సారి user applicationని manually start చేయడం సరైన విధానం కాదు.

ఇక్కడే Windows Service ఉపయోగపడుతుంది.

Windows Service అనేది Windows Operating Systemతో పాటు backgroundలో run అవుతూ, user interaction అవసరం లేకుండా నిరంతరం పని చేయగల application.

Modern .NETలో Windows Service applications కోసం Worker Service + BackgroundService approach విస్తృతంగా ఉపయోగిస్తారు.


1. Windows Service అంటే ఏమిటి?

Windows Service అనేది Windows Operating Systemలో backgroundలో run అయ్యే application.

దీనిని Windows యొక్క Service Control Manager (SCM) manage చేస్తుంది.

SCM ద్వారా మనం:

  • Service Start చేయవచ్చు
  • Service Stop చేయవచ్చు
  • Service Restart చేయవచ్చు
  • Automatic Startup configure చేయవచ్చు
  • Service Failure వచ్చినప్పుడు Restart చేయవచ్చు

సాధారణ Console Application flow:

User
  |
  v
Start Application
  |
  v
Console Window
  |
  v
Application Running

Windows Service flow:

Windows Operating System
        |
        v
Service Control Manager
        |
        v
Order Processing Service
        |
        v
Background Worker
        |
        +----> Database
        |
        +----> External API
        |
        +----> File System
        |
        +----> Message Queue

2. Windows Services ఎందుకు ఉపయోగించాలి?

ఒక E-Commerce Applicationను ఉదాహరణగా తీసుకుందాం.

Customer ఒక Order place చేసినప్పుడు Web API ఆ Orderను Databaseలో save చేస్తుంది.

అయితే Order processing మొత్తం HTTP requestలో చేయడం అవసరం లేదు.

దానికి బదులుగా backgroundలో ఒక Windows Serviceని run చేయవచ్చు.

Customer
   |
   v
Angular Application
   |
   v
.NET Web API
   |
   v
SQL Server
   |
   | Pending Orders
   v
Windows Service
   |
   +---- Process Order
   |
   +---- Generate Invoice
   |
   +---- Update Status
   |
   +---- Send Notification

Windows Serviceను ఉపయోగించగల కొన్ని real-time scenarios:

1. Order Processing

Pending Ordersను backgroundలో process చేయడం.

2. File Processing

ఒక folderలోకి వచ్చే filesను automatically process చేయడం.

3. Data Synchronization

ఒక databaseలోని dataను మరో systemకు synchronize చేయడం.

4. Notification Service

Email, SMS లేదా push notifications పంపించడం.

5. Report Generation

రోజువారీ లేదా hourly reports generate చేయడం.


3. Worker Service మరియు Windows Service మధ్య తేడా

ఈ రెండు conceptsను చాలామంది ఒకటే అనుకుంటారు.

కానీ అవి ఒకటి కావు.

Worker Service

Worker Service అనేది long-running background tasks కోసం ఉపయోగించే .NET application model.

Windows Service

Windows Service అనేది Windows Operating System ద్వారా background applicationను manage చేసే hosting model.

అంటే:

Worker Service
      +
Windows Service Integration
      |
      v
Windows Service

Modern .NETలో సాధారణంగా:

Worker Service
      |
      v
BackgroundService
      |
      v
AddWindowsService()
      |
      v
Windows Service

4. Real-Time Example – Order Processing Service

ఇప్పుడు మనం ఒక real-time projectను build చేద్దాం.

మన application పేరు:

OrderProcessingService

Requirement:

ప్రతి 30 secondsకు SQL Serverలో Pending Orders ఉన్నాయా లేదా check చేసి వాటిని process చేయాలి.

Flow:

SQL Server
    |
    | Pending Orders
    v
Windows Service
    |
    v
Get Orders
    |
    v
Process Order
    |
    v
Generate Invoice
    |
    v
Update Status
    |
    v
Log Result

5. Prerequisites

మీ systemలో ఇవి ఉండాలి:

  • Windows Operating System
  • .NET SDK
  • Visual Studio లేదా VS Code
  • SQL Server
  • Windows Service install చేయడానికి Administrator privileges

6. Worker Service Project Create చేయడం

.NET CLI ద్వారా:

dotnet new worker -n OrderProcessingService

Project folderలోకి వెళ్లండి:

cd OrderProcessingService

Applicationను run చేయండి:

dotnet run

ఇది Worker Service templateతో ఒక background applicationను create చేస్తుంది.


7. Project Structure

మన project structure ఇలా ఉండవచ్చు:

OrderProcessingService
│
├── Program.cs
├── Worker.cs
├── appsettings.json
│
├── Models
│   └── Order.cs
│
├── Services
│   ├── IOrderProcessor.cs
│   └── OrderProcessor.cs
│
└── Data
    └── OrderRepository.cs

ఇక్కడ ముఖ్యమైన architecture:

Worker
  |
  v
Business Service
  |
  v
Repository
  |
  v
Database

Workerలో business logic మొత్తం రాయకుండా separate servicesగా ఉంచడం మంచి practice.


8. Windows Service Package Install చేయడం

ఈ NuGet packageను install చేయండి:

dotnet add package Microsoft.Extensions.Hosting.WindowsServices

ఇది .NET applicationను Windows Serviceగా host చేయడానికి అవసరమైన integrationను అందిస్తుంది.


9. BackgroundService అంటే ఏమిటి?

మన Worker class సాధారణంగా:

BackgroundService

నుంచి inherit అవుతుంది.

Example:

public class Worker : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // Background processing

            await Task.Delay(
                TimeSpan.FromSeconds(30),
                stoppingToken);
        }
    }
}

ఇక్కడ ముఖ్యమైన method:

ExecuteAsync()

ఇదే methodలో మన background processing logic ఉంటుంది.


10. CancellationToken అంటే ఏమిటి?

Windows Serviceను stop చేసినప్పుడు application వెంటనే terminate కాకుండా gracefulగా shutdown అవ్వాలి.

అందుకోసం .NET మనకు:

CancellationToken

ఇస్తుంది.

ఉదాహరణ:

while (!stoppingToken.IsCancellationRequested)

దీని అర్థం:

Windows Service stop request వచ్చే వరకు background processing కొనసాగించు.

Windows Service stop చేసినప్పుడు:

Windows
   |
   v
Stop Request
   |
   v
CancellationToken
   |
   v
Worker Stops

11. Program.cs

ఇప్పుడు Program.cs configure చేద్దాం.

using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "Order Processing Service";
});

builder.Services.AddHostedService<Worker>();

var host = builder.Build();

host.Run();

ఇక్కడ ముఖ్యమైన line:

builder.Services.AddWindowsService();

ఇది applicationను Windows Service environmentలో host చేయడానికి configure చేస్తుంది.


12. Worker.cs

ఇప్పుడు Worker implementation:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            "Order Processing Service started.");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                _logger.LogInformation(
                    "Checking for pending orders.");

                await ProcessOrders(stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Error while processing orders.");
            }

            await Task.Delay(
                TimeSpan.FromSeconds(30),
                stoppingToken);
        }

        _logger.LogInformation(
            "Order Processing Service stopped.");
    }

    private async Task ProcessOrders(
        CancellationToken cancellationToken)
    {
        // Order processing logic

        await Task.CompletedTask;
    }
}

13. Task.Delay ఎందుకు ఉపయోగించాలి?

మన requirement:

ప్రతి 30 secondsకు Orders check చేయాలి.

అందుకే:

await Task.Delay(
    TimeSpan.FromSeconds(30),
    stoppingToken);

ఉపయోగించవచ్చు.

Flow:

Service Starts
      |
      v
Process Orders
      |
      v
Wait 30 Seconds
      |
      v
Process Orders
      |
      v
Wait 30 Seconds
      |
      v
Continue...

14. Thread.Sleep ఎందుకు Avoid చేయాలి?

ఇలా రాయడం మంచిది కాదు:

Thread.Sleep(30000);

దానికి బదులుగా:

await Task.Delay(
    TimeSpan.FromSeconds(30),
    stoppingToken);

ఉపయోగించడం మంచిది.

Thread.Sleep() threadను block చేస్తుంది.

Task.Delay() asynchronous waitingను ఉపయోగిస్తుంది మరియు cancellationను handle చేయగలదు.


15. Order Model Create చేయడం

Models/Order.cs create చేయండి.

namespace OrderProcessingService.Models;

public class Order
{
    public int Id { get; set; }

    public string OrderNumber { get; set; } = string.Empty;

    public decimal Amount { get; set; }

    public string Status { get; set; } = string.Empty;

    public DateTime CreatedDate { get; set; }
}

16. SQL Server Table Create చేయడం

SQL Serverలో:

CREATE TABLE Orders
(
    Id INT IDENTITY PRIMARY KEY,

    OrderNumber VARCHAR(50) NOT NULL,

    Amount DECIMAL(18,2) NOT NULL,

    Status VARCHAR(20) NOT NULL,

    CreatedDate DATETIME2 NOT NULL
);

కొన్ని sample orders:

INSERT INTO Orders
(
    OrderNumber,
    Amount,
    Status,
    CreatedDate
)
VALUES
(
    'ORD1001',
    2500,
    'Pending',
    GETDATE()
);

INSERT INTO Orders
(
    OrderNumber,
    Amount,
    Status,
    CreatedDate
)
VALUES
(
    'ORD1002',
    3500,
    'Pending',
    GETDATE()
);

17. Repository Create చేయడం

Data/OrderRepository.cs:

using Microsoft.Data.SqlClient;
using OrderProcessingService.Models;

public class OrderRepository
{
    private readonly string _connectionString;

    public OrderRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task<List<Order>> GetPendingOrdersAsync(
        CancellationToken cancellationToken)
    {
        var orders = new List<Order>();

        using var connection =
            new SqlConnection(_connectionString);

        await connection.OpenAsync(cancellationToken);

        var command = new SqlCommand(
            """
            SELECT TOP 10
                   Id,
                   OrderNumber,
                   Amount,
                   Status,
                   CreatedDate
            FROM Orders
            WHERE Status = 'Pending'
            ORDER BY Id
            """,
            connection);

        using var reader =
            await command.ExecuteReaderAsync(
                cancellationToken);

        while (await reader.ReadAsync(cancellationToken))
        {
            orders.Add(new Order
            {
                Id = reader.GetInt32(0),
                OrderNumber = reader.GetString(1),
                Amount = reader.GetDecimal(2),
                Status = reader.GetString(3),
                CreatedDate = reader.GetDateTime(4)
            });
        }

        return orders;
    }
}

18. Dependency Injection ఉపయోగించడం

Repositoryను Dependency Injectionలో register చేయవచ్చు.

builder.Services.AddSingleton<OrderRepository>();

Business service కోసం:

builder.Services.AddScoped<IOrderProcessor, OrderProcessor>();

ఇక్కడ ఒక ముఖ్యమైన విషయం:

BackgroundService సాధారణంగా singleton lifetimeలో ఉంటుంది.

కానీ మనం Scoped servicesను ఉపయోగించాలంటే:

IServiceScopeFactory

ద్వారా కొత్త scope create చేయాలి.


19. Order Processor

Services/IOrderProcessor.cs:

public interface IOrderProcessor
{
    Task ProcessAsync(
        CancellationToken cancellationToken);
}

Implementation:

public class OrderProcessor : IOrderProcessor
{
    private readonly OrderRepository _repository;
    private readonly ILogger<OrderProcessor> _logger;

    public OrderProcessor(
        OrderRepository repository,
        ILogger<OrderProcessor> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public async Task ProcessAsync(
        CancellationToken cancellationToken)
    {
        var orders =
            await _repository.GetPendingOrdersAsync(
                cancellationToken);

        foreach (var order in orders)
        {
            _logger.LogInformation(
                "Processing order {OrderNumber}",
                order.OrderNumber);

            // Business logic

            _logger.LogInformation(
                "Order {OrderNumber} processed successfully.",
                order.OrderNumber);
        }
    }
}

20. Workerలో Dependency Injection

ఇప్పుడు Worker:

public class Worker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<Worker> _logger;

    public Worker(
        IServiceScopeFactory scopeFactory,
        ILogger<Worker> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            "Order Processing Service started.");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                using var scope =
                    _scopeFactory.CreateScope();

                var processor =
                    scope.ServiceProvider
                        .GetRequiredService<IOrderProcessor>();

                await processor.ProcessAsync(
                    stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Unexpected error.");
            }

            await Task.Delay(
                TimeSpan.FromSeconds(30),
                stoppingToken);
        }

        _logger.LogInformation(
            "Order Processing Service stopped.");
    }
}

ఇప్పుడు architecture cleanగా ఉంటుంది:

Worker
  |
  v
IOrderProcessor
  |
  v
OrderProcessor
  |
  v
OrderRepository
  |
  v
SQL Server

21. appsettings.json

Configuration valuesను codeలో hard-code చేయకూడదు.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=OrderDb;Trusted_Connection=True;TrustServerCertificate=True"
  },

  "WorkerSettings": {
    "IntervalSeconds": 30,
    "BatchSize": 10
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

ఇప్పుడు interval:

30 seconds

గా configure చేశాం.

రేపు దీనిని 60 seconds చేయాలంటే code మార్చాల్సిన అవసరం లేదు.


22. Configuration Class

public class WorkerSettings
{
    public int IntervalSeconds { get; set; }

    public int BatchSize { get; set; }
}

Program.csలో:

builder.Services.Configure<WorkerSettings>(
    builder.Configuration.GetSection("WorkerSettings"));

23. Logging

Windows Serviceలో application సాధారణంగా console windowలో కనిపించదు.

కాబట్టి logging చాలా ముఖ్యమైనది.

_logger.LogInformation(
    "Order {OrderNumber} processed.",
    order.OrderNumber);

ఇతర logging levels:

_logger.LogDebug("Debug information");

_logger.LogInformation("Information");

_logger.LogWarning("Warning");

_logger.LogError("Error");

_logger.LogCritical("Critical failure");

24. Windows Event Viewer

Windows Service productionలో run అవుతున్నప్పుడు logsను Windows Event Viewerలో చూడవచ్చు.

Open:

Start
  |
  v
Event Viewer
  |
  v
Windows Logs
  |
  v
Application

ఇక్కడ application/serviceకి సంబంధించిన errors మరియు information eventsను చూడవచ్చు.


25. Console Application vs Windows Service

Development సమయంలో:

dotnet run

అని run చేస్తే application console processగా run అవుతుంది.

Productionలో:

Windows
   |
   v
Service Control Manager
   |
   v
Order Processing Service
   |
   v
Worker

అంటే అదే Worker applicationను developmentలో consoleగా test చేసి, productionలో Windows Serviceగా deploy చేయవచ్చు.


26. Application Publish చేయడం

Production deploymentకు ముందు applicationను publish చేయాలి.

Windows x64 కోసం:

dotnet publish -c Release -r win-x64 --self-contained true

Single executableగా publish చేయాలంటే:

dotnet publish -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true

Published files సాధారణంగా:

bin
 └── Release
      └── netX.X
           └── win-x64
                └── publish

లో ఉంటాయి.

netX.X మీ project ఉపయోగిస్తున్న .NET versionను సూచిస్తుంది.


27. Windows Service Install చేయడం

PowerShell లేదా Command Promptను Administratorగా open చేయండి.

ఉదాహరణ:

sc.exe create "Order Processing Service" binPath= "C:\Services\OrderProcessingService\OrderProcessingService.exe"

Service create అయిన తర్వాత:

[SC] CreateService SUCCESS

అని కనిపిస్తుంది.


28. Service Start చేయడం

sc.exe start "Order Processing Service"

లేదా:

Services
   |
   v
Order Processing Service
   |
   v
Right Click
   |
   v
Start

29. Windows Service Lifecycle

మొత్తం lifecycle:

Windows Boot
     |
     v
Service Control Manager
     |
     v
Start Service
     |
     v
.NET Host
     |
     v
BackgroundService
     |
     v
ExecuteAsync()
     |
     v
Process Orders
     |
     v
Wait
     |
     +--------+
              |
              v
        Process Again

Windows Service stop చేసినప్పుడు:

Stop Request
     |
     v
CancellationToken
     |
     v
ExecuteAsync exits
     |
     v
Host Shutdown
     |
     v
Service Stopped

30. Service Stop చేయడం

sc.exe stop "Order Processing Service"

లేదా Services windowలో:

Order Processing Service
       |
       v
Stop

31. Service Delete చేయడం

Service పూర్తిగా remove చేయాలంటే:

sc.exe stop "Order Processing Service"

sc.exe delete "Order Processing Service"

32. Automatic Startup Configure చేయడం

Production Windows Service సాధారణంగా Windows start అయినప్పుడు automatically start అవ్వాలి.

sc.exe config "Order Processing Service" start= auto

ఇప్పుడు Windows restart అయినప్పుడు Service కూడా automatically start అవుతుంది.


33. Service Recovery

Production environmentలో service crash అయితే ఏమవుతుంది?

ఉదాహరణ:

Order Processing Service
        |
        v
Unexpected Error
        |
        v
Service Stops

మనకు కావాల్సింది:

Service Failure
      |
      v
Windows Service Manager
      |
      v
Restart Service

Service recovery configure చేయడానికి:

sc.exe failure "Order Processing Service" reset= 86400 actions= restart/60000/restart/60000/run/1000

దీంతో service failure వచ్చినప్పుడు configured recovery action ప్రకారం restart చేయవచ్చు.


34. Recovery ఎందుకు ముఖ్యమైనది?

Production serverలో ఉదాహరణకు రాత్రి 2 AMకి service crash అయిందనుకుందాం.

Recovery లేకపోతే:

Service Crashes
      |
      v
Processing Stops
      |
      v
Manual Intervention

Recovery ఉంటే:

Service Crashes
      |
      v
Windows Detects Failure
      |
      v
Automatic Restart
      |
      v
Processing Continues

35. Exception Handling

Background Serviceలో exception handling చాలా ముఖ్యమైనది.

Bad approach:

while (true)
{
    await ProcessOrders();
}

Better:

while (!stoppingToken.IsCancellationRequested)
{
    try
    {
        await ProcessOrders(stoppingToken);
    }
    catch (Exception ex)
    {
        _logger.LogError(
            ex,
            "Error processing orders.");
    }

    await Task.Delay(
        TimeSpan.FromSeconds(30),
        stoppingToken);
}

అయితే ప్రతి exceptionను catch చేసి ignore చేయడం కూడా సరైన approach కాదు.

కొన్ని errors applicationను stop చేసి recovery mechanism ద్వారా restart చేయాల్సినంత seriousగా ఉండవచ్చు.


36. Graceful Shutdown

Suppose Order 1001 process అవుతోంది.

అదే సమయంలో Windows Service stop command వచ్చింది.

Processing Order 1001
        |
        v
Windows Stop Request
        |
        v
CancellationToken

Service కొత్త workను తీసుకోకుండా, ప్రస్తుతం జరుగుతున్న operationను safeగా complete చేసి shutdown అవ్వాలి.

అందుకే CancellationTokenను అన్ని layersకి pass చేయాలి.

Worker
  |
  v
Processor
  |
  v
Repository
  |
  v
Database

ఉదాహరణ:

await connection.OpenAsync(
    cancellationToken);

మరియు:

await command.ExecuteReaderAsync(
    cancellationToken);

37. Long Blocking Operationsను Avoid చేయాలి

Avoid:

Thread.Sleep(...);

అలాగే అవసరం ఉన్న చోట synchronous network/database callsను avoid చేయండి.

Prefer:

await httpClient.GetAsync(
    url,
    cancellationToken);

Database కోసం:

await command.ExecuteNonQueryAsync(
    cancellationToken);

దీంతో application responsiveగా ఉండటమే కాకుండా graceful shutdown కూడా సులభమవుతుంది.


38. Third-Party APIని Call చేయడం

Suppose Order process చేసిన తర్వాత Payment APIకి notification పంపాలి.

HttpClientFactory ఉపయోగించవచ్చు:

builder.Services.AddHttpClient(
    "PaymentApi",
    client =>
    {
        client.BaseAddress =
            new Uri("https://api.example.com/");
    });

Payment service:

public class PaymentService
{
    private readonly IHttpClientFactory _httpClientFactory;

    public PaymentService(
        IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task NotifyPaymentAsync(
        int orderId,
        CancellationToken cancellationToken)
    {
        var client =
            _httpClientFactory.CreateClient("PaymentApi");

        await client.PostAsJsonAsync(
            "payments/process",
            new
            {
                OrderId = orderId
            },
            cancellationToken);
    }
}

39. Production Architecture

Real-time enterprise applicationలో architecture ఇలా ఉండవచ్చు:

                 ┌─────────────────────┐
                 │      SQL Server     │
                 │                     │
                 │ Pending Orders      │
                 └──────────┬──────────┘
                            │
                            ▼
                 ┌─────────────────────┐
                 │  Windows Service    │
                 │                     │
                 │ BackgroundService   │
                 └──────────┬──────────┘
                            │
                            ▼
                 ┌─────────────────────┐
                 │ Order Processor     │
                 │                     │
                 │ Business Logic      │
                 └──────────┬──────────┘
                            │
             ┌──────────────┼──────────────┐
             ▼              ▼              ▼
       SQL Server       Payment API    Notification API
             │              │              │
             └──────────────┼──────────────┘
                            ▼
                       Logging

40. Duplicate Processing Problem

ఇది productionలో చాలా ముఖ్యమైన విషయం.

Suppose:

Worker
   |
   v
Get Order 1001
   |
   v
Start Processing

Processing మధ్యలో service crash అయింది.

Restart అయిన తర్వాత:

Worker
   |
   v
Get Order 1001 Again

ఇప్పుడు అదే Order రెండుసార్లు process అయ్యే అవకాశం ఉంది.

దీనిని Duplicate Processing అంటారు.

దీన్ని prevent చేయడానికి:

  • Idempotency
  • Status transitions
  • Database constraints
  • Transactions
  • Outbox/Inbox patterns
  • Message deduplication

వంటి techniques ఉపయోగించవచ్చు.


41. Order Status Design

కేవలం:

Pending
   |
   v
Completed

అనే statuses కాకుండా:

Pending
   |
   v
Processing
   |
   v
Completed

మరియు failure కోసం:

Processing
   |
   v
Failed

ఉంచవచ్చు.

Complete flow:

Pending
   |
   v
Processing
   |
   +------> Failed
   |
   v
Completed

దీంతో Order ఏ stageలో ఉందో మనకు స్పష్టంగా తెలుస్తుంది.


42. Database Transactions

Critical database operations కోసం transaction ఉపయోగించవచ్చు.

Conceptually:

BEGIN TRANSACTION

Get Pending Order

Change Status = Processing

Perform Database Operations

Change Status = Completed

COMMIT

ఏదైనా database operation fail అయితే:

ROLLBACK

అయితే external API calls వంటి slow operationsను database transactionలో ఎక్కువసేపు ఉంచడం సాధారణంగా మంచిది కాదు.

అలాంటి distributed workflows కోసం:

  • Outbox Pattern
  • Inbox Pattern
  • Idempotency
  • Saga Pattern
  • Message Queue

వంటి patterns ఉపయోగించవచ్చు.


43. Windows Service + Message Queue

Large enterprise applicationsలో databaseను ప్రతి 30 secondsకు poll చేయడం కంటే Message Queue ఉపయోగించడం మంచి design కావచ్చు.

ఉదాహరణ:

Web API
   |
   v
Azure Service Bus / RabbitMQ
   |
   v
Windows Service
   |
   v
Order Processor

Worker queueలోని messagesను process చేస్తుంది.


44. Azure Service Busతో Windows Service

Architecture:

Customer
   |
   v
Web API
   |
   v
Azure Service Bus
   |
   v
Windows Service
   |
   v
Order Processing

Conceptually:

while (!stoppingToken.IsCancellationRequested)
{
    var message =
        await ReceiveMessageAsync(
            stoppingToken);

    await ProcessMessageAsync(
        message,
        stoppingToken);
}

ఈ architecture వల్ల Web API మరియు background processing మధ్య loose coupling ఏర్పడుతుంది.


45. Health Monitoring

Production Windows Serviceను monitor చేయాలి.

ముఖ్యమైన metrics:

Service Status
Last Successful Processing
Last Failure
Orders Processed
Processing Duration
Database Connectivity
External API Availability
CPU Usage
Memory Usage

ఉదాహరణ:

Order Processing Service

Status: Running

Orders Processed: 15,230

Last Successful Run:
2026-08-31 12:15:00

Last Error:
None

Average Processing Time:
1.8 seconds

46. Environment-specific Configuration

Configurationను environment ఆధారంగా వేరు చేయవచ్చు.

appsettings.json
appsettings.Development.json
appsettings.Production.json

Development:

{
  "WorkerSettings": {
    "IntervalSeconds": 10
  }
}

Production:

{
  "WorkerSettings": {
    "IntervalSeconds": 60
  }
}

47. Security Best Practices

Connection strings మరియు passwordsను source codeలో hard-code చేయకండి.

Bad:

var connectionString =
    "Server=...;User Id=admin;Password=12345";

Better approaches:

  • Windows Authentication
  • Environment Configuration
  • Secret Management
  • Azure Key Vault
  • Secure configuration providers

అలాగే Windows Serviceకి అవసరమైన permissions మాత్రమే ఇవ్వాలి.

అనవసరంగా Administrator privileges ఇవ్వకండి.


48. Service Account

Windows Service ఒక Windows accountతో run అవుతుంది.

Common options:

Local System
Local Service
Network Service
Custom Service Account

Productionలో least privilege principle పాటించాలి.

అంటే Service accountకి అవసరమైన:

Database Access
File System Access
Network Access
API Access
Certificate Access
Log Access

మాత్రమే ఇవ్వాలి.


49. File Processing Service

Windows Service file processingకు చాలా ఉపయోగకరంగా ఉంటుంది.

ఉదాహరణ:

C:\Input
     |
     v
Windows Service
     |
     v
Validate File
     |
     v
Process File
     |
     v
Archive File

కానీ Service accountకి folder permissions ఉన్నాయో లేదో తప్పనిసరిగా check చేయాలి.

చాలా సందర్భాల్లో:

Console Application
      |
      v
Works

కానీ:

Windows Service
      |
      v
Access Denied

అవుతుంది.

దానికి కారణం రెండూ వేర్వేరు Windows accountsతో run అవుతూ ఉండవచ్చు.


50. Directory.GetCurrentDirectory() విషయంలో జాగ్రత్త

Windows Serviceలో:

Directory.GetCurrentDirectory()

పై ఆధారపడటం avoid చేయడం మంచిది.

Application files కోసం:

AppContext.BaseDirectory

వంటి application-relative path approach ఉపయోగించవచ్చు.


51. Deployment Process

Enterprise environmentలో deployment flow:

Developer
   |
   v
Git Repository
   |
   v
CI/CD Pipeline
   |
   v
dotnet build
   |
   v
dotnet test
   |
   v
dotnet publish
   |
   v
Windows Server
   |
   v
Stop Service
   |
   v
Deploy New Version
   |
   v
Start Service
   |
   v
Verify Logs

Azure DevOps వంటి CI/CD toolsతో ఈ processను automate చేయవచ్చు.


52. Service Update

Version 1:

OrderProcessingService v1

తర్వాత Version 2 release చేశామని అనుకుందాం.

Typical deployment:

sc.exe stop "Order Processing Service"

తర్వాత కొత్త published files deploy చేయాలి.

తర్వాత:

sc.exe start "Order Processing Service"

అని start చేయాలి.

Critical processing ఉన్న systemsలో deployment సమయంలో in-flight jobs ఎలా handle అవుతాయో ముందుగానే design చేయాలి.


53. Troubleshooting

Problem 1: Service Start కావడం లేదు

Check చేయాల్సినవి:

Event Viewer
Executable Path
Service Account Permissions
Configuration
Connection String
Required Files
.NET Runtime

Problem 2: Service Start అయ్యి వెంటనే Stop అవుతోంది

Possible reasons:

Unhandled Exception
Invalid Configuration
Missing Dependency
Database Connection Failure
Startup Exception
Invalid Executable

Event Viewer మరియు application logs check చేయండి.


Problem 3: dotnet runలో పనిచేస్తుంది కానీ Windows Serviceగా పనిచేయడం లేదు

Possible reasons:

Different Service Account
File Permission
Different Working Directory
Environment Configuration
Missing Configuration File
Database Authentication
Network Permission

Problem 4: Database Connection Failure

Check:

SQL Server Availability
Connection String
Authentication
Firewall
Service Account
Database Permissions

Problem 5: Service Repeatedly Restart అవుతోంది

Check:

Event Viewer
Application Logs
Recovery Configuration
Unhandled Exceptions
CPU Usage
Memory Usage
External Dependencies

54. Complete Architecture

Production-ready Windows Service architecture:

                  ┌─────────────────────┐
                  │ Windows Server      │
                  │                     │
                  │ Service Control     │
                  │ Manager             │
                  └──────────┬──────────┘
                             │
                             ▼
                  ┌─────────────────────┐
                  │ Order Worker        │
                  │                     │
                  │ BackgroundService   │
                  └──────────┬──────────┘
                             │
                             ▼
                  ┌─────────────────────┐
                  │ Order Processor     │
                  │                     │
                  │ Business Rules      │
                  └───────┬───────┬─────┘
                          │       │
                ┌─────────┘       └─────────┐
                ▼                           ▼
        ┌──────────────┐             ┌──────────────┐
        │ SQL Server   │             │ External API │
        └──────────────┘             └──────────────┘
                          │
                          ▼
                    ┌───────────┐
                    │ Event Log │
                    └───────────┘

55. End-to-End Flow

మొత్తం application ఎలా పనిచేస్తుందో step-by-step చూద్దాం.

Step 1 – Windows Start అవుతుంది

Windows Server

Step 2 – Service Control Manager Serviceను start చేస్తుంది

SCM
 |
 v
Order Processing Service

Step 3 – .NET Host start అవుతుంది

Host
 |
 v
Dependency Injection
 |
 v
BackgroundService

Step 4 – Worker start అవుతుంది

Worker.ExecuteAsync()

Step 5 – Worker Pending Ordersను retrieve చేస్తుంది

SQL Server
 |
 v
Pending Orders

Step 6 – Business Logic execute అవుతుంది

OrderProcessor

Step 7 – Order Status update అవుతుంది

Pending
   |
   v
Processing
   |
   v
Completed

Step 8 – Logging జరుగుతుంది

Event Log

Step 9 – Worker wait చేస్తుంది

30 Seconds

Step 10 – మళ్లీ processing ప్రారంభమవుతుంది

Process
  |
  v
Wait
  |
  v
Process
  |
  v
Wait

Step 11 – Windows Stop Request పంపుతుంది

CancellationToken

Step 12 – Worker gracefulగా shutdown అవుతుంది

ExecuteAsync()
     |
     v
Host Shutdown
     |
     v
Service Stopped

56. PeriodicTimer ఉపయోగించడం

Periodic background processing కోసం PeriodicTimer కూడా ఉపయోగించవచ్చు.

protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    using var timer =
        new PeriodicTimer(
            TimeSpan.FromSeconds(30));

    while (await timer.WaitForNextTickAsync(
        stoppingToken))
    {
        await ProcessOrders(
            stoppingToken);
    }
}

ఇది periodic processing codeను cleanగా మరియు readableగా ఉంచుతుంది.


57. Complete Worker Example

Production-style simplified Worker:

using Microsoft.Extensions.Hosting;

public class Worker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<Worker> _logger;

    public Worker(
        IServiceScopeFactory scopeFactory,
        ILogger<Worker> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        _logger.LogInformation(
            "Order Processing Service started.");

        using var timer =
            new PeriodicTimer(
                TimeSpan.FromSeconds(30));

        try
        {
            while (await timer.WaitForNextTickAsync(
                stoppingToken))
            {
                try
                {
                    using var scope =
                        _scopeFactory.CreateScope();

                    var processor =
                        scope.ServiceProvider
                            .GetRequiredService<IOrderProcessor>();

                    await processor.ProcessAsync(
                        stoppingToken);
                }
                catch (OperationCanceledException)
                    when (stoppingToken.IsCancellationRequested)
                {
                    break;
                }
                catch (Exception ex)
                {
                    _logger.LogError(
                        ex,
                        "Error occurred while processing orders.");
                }
            }
        }
        catch (OperationCanceledException)
            when (stoppingToken.IsCancellationRequested)
        {
            // Expected during shutdown.
        }

        _logger.LogInformation(
            "Order Processing Service stopped.");
    }
}

58. Complete Program.cs

using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "Order Processing Service";
});

builder.Services.Configure<WorkerSettings>(
    builder.Configuration.GetSection("WorkerSettings"));

var connectionString =
    builder.Configuration.GetConnectionString(
        "DefaultConnection");

builder.Services.AddSingleton(
    new OrderRepository(connectionString!));

builder.Services.AddScoped<IOrderProcessor, OrderProcessor>();

builder.Services.AddHostedService<Worker>();

var host = builder.Build();

host.Run();

59. Important Commands Cheat Sheet

Worker Service Create

dotnet new worker -n OrderProcessingService

Windows Service Package

dotnet add package Microsoft.Extensions.Hosting.WindowsServices

Build

dotnet build

Local Run

dotnet run

Publish

dotnet publish -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true

Create Service

sc.exe create "Order Processing Service" binPath= "C:\Services\OrderProcessingService\OrderProcessingService.exe"

Automatic Startup

sc.exe config "Order Processing Service" start= auto

Start

sc.exe start "Order Processing Service"

Stop

sc.exe stop "Order Processing Service"

Delete

sc.exe delete "Order Processing Service"

Check Recovery Configuration

sc.exe qfailure "Order Processing Service"

60. Windows Service Best Practices

Production Windows Servicesలో ఈ best practices పాటించండి:

  1. BackgroundService ఉపయోగించండి.
  2. Dependency Injection ఉపయోగించండి.
  3. Async programming ఉపయోగించండి.
  4. CancellationTokenను అన్ని layersకి pass చేయండి.
  5. Structured Logging ఉపయోగించండి.
  6. Connection stringsను hard-code చేయకండి.
  7. Secretsను secureగా store చేయండి.
  8. Least-privilege Service Account ఉపయోగించండి.
  9. Service Recovery configure చేయండి.
  10. Duplicate processingను prevent చేయండి.
  11. అవసరమైన చోట database transactions ఉపయోగించండి.
  12. Business logicను Workerలో కాకుండా separate servicesలో ఉంచండి.
  13. Interval మరియు Batch Sizeలను configuration ద్వారా manage చేయండి.
  14. CPU మరియు Memory usage monitor చేయండి.
  15. Event Viewer/Application Logsను monitor చేయండి.
  16. Graceful shutdown implement చేయండి.
  17. Idempotencyను consider చేయండి.
  18. Production deploymentను CI/CD ద్వారా automate చేయండి.
  19. Message Queue అవసరమైతే ఉపయోగించండి.
  20. Service accountకి అవసరమైన permissions మాత్రమే ఇవ్వండి.

61. Windows Service ఎప్పుడు ఉపయోగించాలి?

Windows Server environmentలో continuously background processing అవసరమైనప్పుడు Windows Service మంచి option.

File Processing

Input Folder
     |
     v
Windows Service
     |
     v
Validate File
     |
     v
Process File
     |
     v
Archive File

Order Processing

Database
   |
   v
Windows Service
   |
   v
Process Orders

Data Synchronization

System A
   |
   v
Windows Service
   |
   v
System B

Scheduled Reports

Windows Service
      |
      v
Generate Report
      |
      v
Save PDF
      |
      v
Send Notification

62. Windows Service ఎప్పుడు ఉపయోగించకూడదు?

ప్రతి background taskకు Windows Serviceనే ఉపయోగించాల్సిన అవసరం లేదు.

ఉదాహరణకు:

  • Cloud-native workload
  • Serverless workload
  • Massive horizontal scaling అవసరమైన workload
  • Managed messaging platformతో సులభంగా solve అయ్యే workload
  • Linux-only environment
  • HTTP request processing ప్రధాన responsibilityగా ఉన్న application

Cloud environmentsలో:

Azure Functions
Azure Container Apps
AKS
Azure Service Bus
Cloud Worker Services

వంటి alternativesను consider చేయవచ్చు.


63. Web API vs Windows Service

FeatureWeb APIWindows Service
User RequestYesNo
HTTP EndpointYesఅవసరం లేదు
Background ProcessingLimitedExcellent
Long-running TaskNot primary purposeExcellent
TriggerHTTP RequestTimer/Event/Message
UINoNo
Windows ServicePossibleNative Scenario
Message ProcessingPossibleExcellent

సరళంగా చెప్పాలంటే:

Web API = Request-driven application

Windows Service = Background-driven application


64. BackgroundService vs Windows Service

BackgroundService
       |
       +---- Console Application
       |
       +---- Windows Service
       |
       +---- Container
       |
       +---- Other Host

BackgroundService అనేది long-running background work implement చేయడానికి .NET abstraction.

Windows Service hosting అనేది ఆ Workerను Windows ద్వారా manage చేయడానికి ఒక hosting option.


65. Interview Questions

Q1. Windows Service అంటే ఏమిటి?

Windows Service అనేది Windows Operating Systemలో backgroundలో run అయ్యే long-running application. దీనిని Service Control Manager manage చేస్తుంది.

Q2. BackgroundService అంటే ఏమిటి?

BackgroundService అనేది .NETలో long-running background tasks implement చేయడానికి ఉపయోగించే base class.

Q3. Worker Serviceను Windows Serviceగా ఎలా run చేస్తారు?

Windows Service package install చేసి:

builder.Services.AddWindowsService();

configure చేయాలి.

Q4. ExecuteAsync() అంటే ఏమిటి?

Workerలో background processing జరిగే ప్రధాన asynchronous method.

Q5. CancellationToken ఎందుకు ఉపయోగిస్తారు?

Service stop request వచ్చినప్పుడు applicationను gracefulగా shutdown చేయడానికి.

Q6. Windows Serviceని ఎలా install చేస్తారు?

sc.exe create

ఉపయోగించవచ్చు.

Q7. Windows Serviceని ఎలా start చేస్తారు?

sc.exe start

Q8. Windows Serviceని ఎలా stop చేస్తారు?

sc.exe stop

Q9. Windows Serviceని ఎలా delete చేస్తారు?

sc.exe delete

Q10. Windows Service errors ఎక్కడ చూడవచ్చు?

Event Viewer
→ Windows Logs
→ Application

Q11. Service crash అయితే automatically restart ఎలా చేయాలి?

Windows Service Recovery Actions configure చేయాలి.

Q12. Duplicate Order Processingను ఎలా prevent చేస్తారు?

సాధారణంగా:

Idempotency
Status Transitions
Database Constraints
Transactions
Outbox/Inbox
Message Deduplication

వంటి techniques ఉపయోగిస్తారు.


66. Final Architecture – ఒకసారి గుర్తుంచుకోవాల్సిన Flow

                 Windows Service
                       |
                       v
                BackgroundService
                       |
                       v
                 ExecuteAsync()
                       |
                       v
                CancellationToken
                       |
                       v
                Dependency Injection
                       |
                       v
                 Business Service
                       |
             +---------+---------+
             |                   |
             v                   v
         Database            External API
             |                   |
             +---------+---------+
                       |
                       v
                    Logging
                       |
                       v
                  Monitoring
                       |
                       v
                 Service Recovery

67. Key Concepts – Quick Revision

Windows Service developmentలో ముఖ్యంగా గుర్తుంచుకోవాల్సిన concepts:

Worker Service
      ↓
BackgroundService
      ↓
ExecuteAsync()
      ↓
CancellationToken
      ↓
Dependency Injection
      ↓
Business Processing
      ↓
Logging
      ↓
Configuration
      ↓
Publish
      ↓
Windows Service
      ↓
Service Control Manager
      ↓
Recovery
      ↓
Monitoring

Conclusion

Modern .NETలో Windows Service applicationలను build చేయడానికి Worker Service + BackgroundService approach చాలా useful.

ఒక production-quality Windows Service కేవలం infinite loop కాదు.

దానిలో:

  • Background Processing
  • Dependency Injection
  • Async Programming
  • Cancellation Handling
  • Logging
  • Configuration
  • Exception Handling
  • Security
  • Service Recovery
  • Monitoring
  • Idempotency
  • Database/Queue Integration

వంటి అంశాలు సరిగ్గా design చేయాలి.

సరళంగా గుర్తుంచుకోవాలంటే:

BackgroundService background workను implement చేస్తుంది; Windows Service hosting ద్వారా Windows ఆ application lifecycleను manage చేస్తుంది.

ఈ foundation అర్థమైతే మీరు:

  • Order Processing Services
  • File Processing Services
  • Notification Services
  • Data Synchronization Services
  • Report Generation Services
  • Azure Service Bus Consumers
  • RabbitMQ Consumers
  • Scheduled Background Jobs

వంటి real-time enterprise applicationsను confidently build చేయగలరు.