简体   繁体   中英

What's the accepted way to write a C# TSR?

I'm using C# to write a WCF router which I want to stay running without using the Console.ReadKey "hack". I was wondering if there's an accepted way to do this within C# that's more elegant than

while (true)
    Thread.Sleep(100);

create a windows service project. windows services have persistent lifecycle as compared to standard windows client.

You can get started here .

From msdn:

After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. The Start method passes processing to the application's OnStart method and processes any code you have defined there.

A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped . You can query the Status to determine what state a service is in.

Maybe use a ManualResetEvent?

ManualResetEvent stopEvent = new ManualResetEvent(false);

public void StartService()
{

     service.Open();
     stopEvent.WaitOne()
}

You can then do a stopEvent.Set() when you want the service to terminate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM