Use of Topshelf, use of Topshelf
I. Introduction
Topshelf can be used to create and manage Windows Services. The advantage is that you can create console programs without creating windows Services. Easy to debug.
2. Official Address:
1. Official Website: http://topshelf-project.com/
2. Official documents: https://topshelf.readthedocs.io/en/latest/
3. github address: https://github.com/Topshelf/Topshelf
Iii. Detailed examples
1. Create the console program "Topshelf test", introduce Topshelf in Nuget ,:
You can also use the Nuget command line to introduce it. The command is as follows:
2. Add a class to the project and name it TopshelfTest.
The content is as follows:
public class TopshelfTest { readonly Timer _timer; public TopshelfTest() { _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => { Run(); }; } public void Start() { _timer.Start(); } public void Stop() { _timer.Stop(); } public static void Run() { Console.WriteLine("hello Topshelf"); } }
3. Add the following code to the Main function:
Public static void Main (string [] args) {HostFactory. run (x => {x. runAsLocalSystem (); x. setDescription ("topshelf test"); x. setDisplayName ("topshelftest"); x. setServiceName ("topshelftest"); x. service <TopshelfTest> (s => {s. constructUsing (name => new TopshelfTest (); s. whenStarted (tc => tc. start (); s. whenStopped (tc => tc. stop ());});});}
4. Run the program. The output is as follows. The Run function is executed every second, and "hello Topshelf" is printed once"
5. Install the service:
Open the cmd command as administrator. The command for managing services is as follows:
Install: topshelftest .exe install start: topshelftest .exe start uninstall: topshelftest .exe uninstall to run the command, you need to switch to the program Directory: install the service:
Start the service:
Uninstall the service:
After installation, you can see the installed services in the service:
Iv. Sample Code
Using System; using System. timers; using Topshelf; namespace Topshelf test {public class Program {public static void Main (string [] args) {HostFactory. run (x => {x. runAsLocalSystem (); x. setDescription ("topshelf test"); x. setDisplayName ("topshelftest"); x. setServiceName ("topshelftest"); x. service <TopshelfTest> (s => {s. constructUsing (name => new TopshelfTest (); s. whenStarted (tc => tc. start (); s. whenStopped (tc => tc. stop () ;}) ;}} public class TopshelfTest {readonly Timer _ timer; public TopshelfTest () {_ timer = new Timer (1000) {AutoReset = true}; _ timer. elapsed + = (sender, eventArgs) => {Run () ;};} public void Start () {_ timer. start ();} public void Stop () {_ timer. stop ();} public static void Run () {Console. writeLine ("hello Topshelf ");}}}