Поддержка  •  Дневник  •  Без рекламы  •  О сайте  •  Реклама  •  Поставить баннер  •  Прислать  •  Хроника  •  Translate Гости: 17    Участники: 0 Авторизация Авторизация   Регистрация 
Метод Научного Тыка
RULVEN
Поиск  
Blackball iMag | интернет-журнал
Каталог


Начало » Разработка ПО » Develop and Install a Windows Service in C#
Мне повезёт!

Develop and Install a Windows Service in C#


Добавлено: Пн 16.11.2020 • Sergeant
Источник: источник
Просмотров: 610
Комментарии: 0


What is a Windows Service

  • Enables you to create long-running executable applications that run in their own windows session.
  • Can be automatically started when the computer boots, can be paused and restarted without any user interaction.
  • Easily installable by running the command line utility InstallUtil.exe and passing the path to the service's executable file.

Why a Windows Service?

One of the most common requirements of some businesses is long-running scheduled jobs based on some time interval. For example: sending a newsletter everyday afternoon or send an email alert to the customer for every one hour.

So building a Windows Service could be one of the reliable solutions to do the goal that can do the required job in the behind the scenes without interfering others users on the same computer.

Introduction

This article explains a step-by-step process of developing and installing a Windows Service to do a scheduled job based on a time interval.

Open Visual Studio and from the menus select "File" -> "New" -> "Project...".

A New Project window will open. Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name the project "TestWindowsService" as shown in the following screenshot.

After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that you want to give it. Then click “click here to switch to code view”.

In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the Windows Service starts and the OnStop() triggers when the service stops.

Right-click the TestWindowService project, add a new class and name it "Library.cs". This class will be useful to create the methods that we require in the project. If your TestWindowService is a big project, you can create a ClassLibrary project and reference it to your TestWindowService.

Library.cs

Make the class public and declare it as a Static class.

Create a log method (WriteErrorLog) to log the exceptions.

Create one more log method (WriteErrorLog) to log the custom messages.

Scheduler.cs

Now return to our Scheduler.cs file and declare a Timer.

Write the following code in the OnStart() method and timer1_Tick():

Write the following code in the OnStop() method:

Scheduler.cs [Design]

Now return to the Scheduler.cs [Design] and right-click on the editor window then click "Add Installer".

Then you can see that there will be a new file called "ProjectInstaller.cs" as shown in the following.

Right-click on the "serviceInstaller1" and click "Properties".

Change the ServiceName to "Test Windows Service" (or your own name) and StartType to "Manual" (or you can choose "Automatic" if you need this service to be automatic).

Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".

Build the project to see the .exe file at the location where you created the solution.

That's all. Your Windows Service is all ready to install in your machine.

Installing the Windows Service

Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click "Developer Command Prompt for VS2012".

Type the following command:

cd

in my case it is:

cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug

Next type the following command:

InstallUtil.exe “TestWindowService.exe”

and press Enter.

Here you go, the TestWindowService is installed successfully.

How to start the Windows Service

Since we chose StartType = Manual, we must start the Windows Service manually by visiting the "Services and Applications" window in the computer.

Select the Test Windows Service and click "Start" to start the service. Go to the "TestWindowService.exe" location to see the logs.

LogFile.txt

Since we are tracking our Windows Service by writing some logs to a .txt file called LogFile.txt, we can test the working condition of our Windows Service by looking at this log file.

As you can see in the preceding screen, you can find the LogFile.txt file at the physical location that your TestWindowService solution exists.

Click the LogFile.txt to see the logs, whether our service is doing the job that we set it to do for every 30 seconds.

If you look at the preceding log file, we can prove that our Windows Service is running and doing the job that we wanted on a 30 seconds interval.

Stop the Windows Service

To stop the Windows Service, just click "Stop" link in the Services window by selecting our TestWindowService.

Logfile after stopping our service:

Type the following two commands in the "Developer Command Prompt for VS2012" to uninstall the TestWindowService.exe.

  1. cd
    and press Enter. In my case it is:
    cd C:\Sandbox\WindowServices\TestWindowService\TestWindowService\bin\Debug
  2. InstallUtil.exe /u “TestWindowService.exe”
    And press enter.
    After executing the preceding commands, the TestWindowService will be uninstalled from your computer.

Summary

In this article, I explained how to develop a Windows Service and install it using InstallUtil.exe from a command prompt.

I believe that I have explained each step clearly that can be easily understandable for a beginner to develop and install a Windows Service.



Мне нравится 0   Мне не нравится 0



Комментарии

Чтобы добавить видео с YouTube, нужно написать [@youtube=xxxxx] , где xxxxx – ID видео.


Комментарии: 0
Нет ни одного комментария.
RSS-лента
Поделиться ссылкой:
История успеха: Logitech История успеха: Logitech
Коктейль виски со Швепсом – оригинальные и согревающие рецепты Коктейль виски со Швепсом – оригинальные и согревающие рецепты
Рекомендации и полезные советы по правильному натуральному кормлению кошки Рекомендации и полезные советы по правильному натуральному кормлению кошки
65 фактов о кошках 65 фактов о кошках
Как наступает оргазм и как вести себя при оргазме?
24 популярных экзотических домашних питомца 24 популярных экзотических домашних питомца
Сравнительный возраст кошки и человека Сравнительный возраст кошки и человека
40 способов развлечь кота 40 способов развлечь кота
Корпоративный туалетный этикет
300+ вопросов по JavaScript на собеседовании 300+ вопросов по JavaScript на собеседовании

csharp
Delegates in C#: A comprehensive guide Ср 27.03.2024
Delegates in C#: A comprehensive guide
C# и .NET: Blazor Пн 25.03.2024
C# и .NET: Blazor
Ср 20.03.2024
Creating functions that return multiple values in C#
Задача по языку C#: Игра «Крестики Нолики» в консоли Пн 26.02.2024
Задача по языку C#: Игра «Крестики Нолики» в консоли
Pagination in a .NET Web API with EF Core Ср 21.02.2024
Pagination in a .NET Web API with EF Core
Зачем нужен MediatR? Пн 24.04.2023
Зачем нужен MediatR?
C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development Build applications with C# NET Core, Entity Framework Чт 02.02.2023
C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development Build applications with C# NET Core, Entity Framework
Год: 2019
C# 6 and .NET Core 1.0 Modern Cross-Platform Development Чт 26.01.2023
C# 6 and .NET Core 1.0 Modern Cross-Platform Development
Год: 2016
Concurrency in C# Cookbook Чт 12.01.2023
Concurrency in C# Cookbook
Год: 2019
C# 7 and .NET Core: Modern Cross-Platform Development, 2nd Edition Вт 04.01.2022
C# 7 and .NET Core: Modern Cross-Platform Development, 2nd Edition
Год: 2017
Effective C# (Covers C# 6.0): 50 Specific Ways to Improve Your C#, 3rd Edition Вт 21.12.2021
Effective C# (Covers C# 6.0): 50 Specific Ways to Improve Your C#, 3rd Edition
Год: 2017
C# and XML Primer Чт 09.12.2021
C# and XML Primer
Год: 2017
More Effective C#: 50 Specific Ways to Improve Your C#, 2nd Edition Вт 16.11.2021
More Effective C#: 50 Specific Ways to Improve Your C#, 2nd Edition
Год: 2017
Разработка обслуживаемых программ на языке C# Чт 28.10.2021
Разработка обслуживаемых программ на языке C#
Год: 2017
C# 7 and .NET Core Cookbook Вт 05.10.2021
C# 7 and .NET Core Cookbook
Год: 2017
C# для профессионалов. Тонкости программирования, 3-е издание Вт 11.05.2021
C# для профессионалов. Тонкости программирования, 3-е издание
Год: 2014
C# 6.0 in a Nutshell, 6th Edition Чт 29.04.2021
C# 6.0 in a Nutshell, 6th Edition
Год: 2015
CLR via C#, 4th Edition Вт 30.03.2021
CLR via C#, 4th Edition
Год: 2012
.NET Domain-Driven Design with C# Вт 16.03.2021
.NET Domain-Driven Design with C#
Год: 2008
Pro LINQ: Language Integrated Query in C# 2010 Чт 25.02.2021
Pro LINQ: Language Integrated Query in C# 2010
Год: 2010
Pro LINQ: Language Integrated Query in C# 2008 Вт 23.02.2021
Pro LINQ: Language Integrated Query in C# 2008
Год: 2007
Software Architecture with C# 9 and .NET 5, Second Edition Сб 13.02.2021
Software Architecture with C# 9 and .NET 5, Second Edition
Год: 2020
C# 9 and .NET 5 Сб 13.02.2021
C# 9 and .NET 5
Год: 2020
Компиляция и запуск C# и Blazor внутри браузера Пн 07.12.2020
Компиляция и запуск C# и Blazor внутри браузера
C# 7.0. Карманный справочник Вт 24.11.2020
C# 7.0. Карманный справочник
Год: 2017
Professional C# 6 and .NET Core 1.0 Вт 17.11.2020
Professional C# 6 and .NET Core 1.0
Год: 2016
Пн 16.11.2020
Develop and Install a Windows Service in C#
C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development Вт 10.11.2020
C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development
Год: 2017
C# 8 Quick Syntax Reference Вт 03.11.2020
C# 8 Quick Syntax Reference
Год: 2020
Problem Solving in Data Structures and Algorithms Using C# Вт 27.10.2020
Problem Solving in Data Structures and Algorithms Using C#
Год: 2018
C# 7 и .NET Core. Кросс-платформенная разработка для профессионалов Вт 01.09.2020
C# 7 и .NET Core. Кросс-платформенная разработка для профессионалов
Год: 2018
Язык программирования C# 7 и платформы .NET и .NET Core Вт 25.08.2020
Язык программирования C# 7 и платформы .NET и .NET Core
Год: 2018
The C# Player’s Guide, 3rd Edition Вт 31.12.2019
The C# Player’s Guide, 3rd Edition
Год: 2016
Design Patterns in C# Пн 09.01.2017
Design Patterns in C#
Год: 2012
Язык программирования C# 5.0 и платформа .NET 4.5 Пн 02.01.2017
Язык программирования C# 5.0 и платформа .NET 4.5
Год: 2013
The C# Player's Guide, 2nd Edition Пн 12.12.2016
The C# Player's Guide, 2nd Edition
Год: 2015
C# Programming Yellow Book Пн 21.11.2016
C# Programming Yellow Book
Год: 2015
Pro WPF 4.5 in C#, 4th Edition Пн 11.04.2016
Pro WPF 4.5 in C#, 4th Edition
Год: 2012
Pro Silverlight 5 in C#, 4th Edition Ср 06.04.2016
Pro Silverlight 5 in C#, 4th Edition
Год: 2012
Pro C# 5.0 and the .NET 4.5 Framework, 6th Edition Пн 21.03.2016
Pro C# 5.0 and the .NET 4.5 Framework, 6th Edition
Год: 2012
Pro ASP.NET 4 in C# 2010, 4th Edition Ср 16.03.2016
Pro ASP.NET 4 in C# 2010, 4th Edition
Год: 2010
Pro .NET 4 Parallel Programming in C# Ср 09.03.2016
Pro .NET 4 Parallel Programming in C#
Год: 2010
A Programmer's Guide to C# 5.0, 4th Edition Ср 24.02.2016
A Programmer's Guide to C# 5.0, 4th Edition
Год: 2012
CLR via C#, 3rd Edition Сб 27.10.2012
CLR via C#, 3rd Edition
Год: 2009
Книги
Fundamentals of Software Architecture вчера, 10:13
Fundamentals of Software Architecture
Год: 2020
Refactoring with C# Вт 23.04.2024
Refactoring with C#
Год: 2023
Building IoT Visualizations using Grafana Вт 09.04.2024
Building IoT Visualizations using Grafana
Год: 2022

Разработано на основе BlackNight CMS
Release v.2024-05-05
© 2000–2024 Blackball
Дизайн & программирование:
О сайтеРеклама
Visitors
Web-site performed by Sergey Drozdov
BlackballРекламаСтатистикаПоддержка | МузыкаПлейлистыКиноВидеоИгрыАудиоПрограммыСтатьиКартинкиЮморФорумДневник сайтаПрислать контент