dir.by  
  Search  
Programming, development, testing
Windows Service (using C#)
Create a new application C# Windows Service (library .NET Core and use Worker)
  Looked at 3178 times    
 Create a new application C# Windows Service (library .NET Core and use Worker) 
last updated: 17 April 2023
Download my service with the source code:
MyWorkerServiceCore1.zip ...
Size: 200 kb
Step 1. Open Visual Studio
If you do not have Visual Studio installed you need install Visual Studio...
Open Visual Studio 2022
or
Open Visual Studio 2019
Step 2. Create a new application with type Worker Service
 
The following project will be created:
Step 3. Add the library WindowsServices
Add the NuGet package Microsoft.Extensions.Hosting.WindowsServices.
This package is needed for the program to run as WindowsService.
Step 4. Add a library to save information, errors in the system EventViewer
Add the NuGet package Microsoft.Extensions.Logging.
This package is needed to save information, errors in the system EventViewer.
When the service is running, the only way to save information, errors is to write in EventViewer.
Step 5. Add the code to the file Program.cs
To make the program run as WindowsService
File Program.cs
UseWindowsService();
Initialization EventViewer
File Program.cs
.ConfigureLogging(options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))

...

.Configure<EventLogSettings>(config =>
{
    config.LogName = EventLogName;
    config.SourceName = EventLogSource;
});
Write information in EventViewer
File Worker.cs
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);

 
The result will be like this:
  C#     File Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;

namespace MyWorkerServiceCore1
{
     public class Program
     {
          public static string EventLogName = "My Worker Service1";
          public static string EventLogSource = "My App1";

          public static void Main(string[] args)
          {
               CreateHostBuilder(args).Build().Run();
          }

          public static IHostBuilder CreateHostBuilder(string[] args) =>
               Host.CreateDefaultBuilder(args)
               .ConfigureLogging(options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))
               .ConfigureServices((hostContext, services) =>
               {
                    services.AddHostedService<Worker>()
                    .Configure<EventLogSettings>(config =>
                    {
                         config.LogName = EventLogName;
                         config.SourceName = EventLogSource;
                    });
               }).UseWindowsService();
     }
}
  C#     File Worker.cs
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

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

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

          protected override async Task ExecuteAsync(CancellationToken stoppingToken)
          {
               while (!stoppingToken.IsCancellationRequested)
               {
                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                    await Task.Delay(1000, stoppingToken);
               }
          }
     }
}
Step 6. Launching the project
 
Let's open EventViewer
and see that our program writes information:
 
Note!
To run the program as WindowsService you need:
register the exe file in the system and run it as Windows Service...
 
← Previous topic
Create folder "My Application" under folder "Application and Services logs" | Event Viewer
 
Next topic →
Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker)
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Technology .NET Framework
Create a new application C# Windows Service (.NET Framework)
C# Windows Service (.NET Framework) with the username. Event when user logs in/out of Windows
Create folder "My Application" under folder "Application and Services logs" | Event Viewer
Technology .NET Core
Create a new application C# Windows Service (library .NET Core and use Worker)
Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker)
How to open a Notepad app from C# Windows Service | library .NET Core and use Worker
Doing publish a project (compiling and assembling a project) "C# Windows Service" | library .NET Core using Worker
How to register your exe file as Windows Service. Start/stop your Windows Service on the system Windows | library .NET Core using Worker

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика