惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
Microsoft Security Blog
Microsoft Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
D
DataBreaches.Net
U
Unit 42
P
Proofpoint News Feed
I
InfoQ
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
博客园 - Franky
博客园_首页
IT之家
IT之家
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志

博客园 - 比尔盖房

USACO: Section 1.5 -- PROB Prime Palindromes USACO: Section 1.5 -- PROB Number Triangles USACO: Section 1.4 -- PROB Arithmetic Progressions USACO: Section 1.3 -- PROB Prime Cryptarithm USACO: Section 1.3 -- PROB Barn Repair USACO: Section 1.3 -- PROB Mixing Milk USACO: Section 1.2 -- PROB Dual Palindromes USACO: Section 1.2 -- PROB Palindromic Squares Programming Pearls: Chatper3 Problem6 [Form letter generator] Programming Pearls: Chatper3 Problem5 [Hyphenation Words] Programming Pearls: Chatper3 Problem4 [Dates Caculation] Programming Pearls: Chatper3 Problem3 [Print Banner] Studying Probability Theory Studying "Concrete Mathematics" Studying "Introduction to Algorithms" Testing SEH tips How DebuggerRCThread is lauched? Public Symbols vs Private Symbols[zt] The magic of NativeWindow-- How does .Net Winform manage Win32 controls
.Net Windows Service
比尔盖房 · 2006-08-07 · via 博客园 - 比尔盖房

static void Main()
{
    System.ServiceProcess.ServiceBase[] ServicesToRun;

    // More than one user Service may run within the same process. To add
    // another service to this process, change the following line to
    // create a second service object. For example,
    //
    //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
    //
    ServicesToRun = new System.ServiceProcess.ServiceBase[] new Service1() };

    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

ServiceBase.Run()
{
1. Initialize each ServiceEntry structure(setting the all the callback routines)
2. Invoke StartServiceCtrlDispatcher();
3. Write eventlog if StartServiceCtrlDispatcher failed.
}

ServiceBase.ServiceMainCallback()
{
1. Call RegisterServiceCtrlHandlerEx
2. Set SERVICE_START_PENDING
3. Start a new thread and wait it to invoke OnStart:

this.startCompletedSignal = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(
new WaitCallback(this.ServiceQueuedMainCallback), textArray1);
this.startCompletedSignal.WaitOne();

}

private void ServiceQueuedMainCallback(object state)
{
      
string[] textArray1 = (string[]) state;
      try
      
{
            this.OnStart(textArray1);
            
this.WriteEventLogEntry(Res.GetString("StartSuccessful"));
            
this.status.currentState = 4;
      }

      
catch (Exception exception1)
      
{
            
this
.WriteEventLogEntry(Res.GetString("StartFailed", new object[] { exception1.ToString() }), EventLogEntryType.Error);
            
this.status.currentState = 1;
      }

      
this.startCompletedSignal.Set();
}


 

Note:
1. This worker thread method catches all exceptions in OnStart method.
2. The currentState is set to SERVICE_RUNNING(4)
3. Start success or failed is logged automatically.

unsafe ServiceBase.ServiceCommandCallback() //HandlerEx func
{
1. For Stop/Pause operations, the general priciple is setting the status to PENDING, then use DeferredHandlerDelegate to invoke DeferredStop(or DeferredPause)
2. OnContinue, OnShutdown and OnCustomCommand are all called directly. All exceptions in these methods are caught and all operations success/failure are logged to eventlog.
}

private unsafe void DeferredStop()
{
      
fixed (NativeMethods.SERVICE_STATUS* service_statusRef1 = &this.status)
      
{
            
int num1 = this.status.currentState;
            
this.status.checkPoint = 0;
            
this.status.waitHint = 0;
            
this.status.currentState = 3;
            NativeMethods.SetServiceStatus(
this.statusHandle, service_statusRef1);
            try
            
{
                  this.OnStop();
                  
this.WriteEventLogEntry(Res.GetString("StopSuccessful"));
                  
this.status.currentState = 1;
                  NativeMethods.SetServiceStatus(
this.statusHandle, service_statusRef1);
            }

            
catch (StackOverflowException)
            
{
                  
throw;
            }

            
catch (OutOfMemoryException)
            
{
                  
throw;
            }

            
catch (ThreadAbortException)
            
{
                  
throw;
            }

            
catch (Exception exception1)
            
{
                  
this
.WriteEventLogEntry(Res.GetString("StopFailed", new object[] { exception1.ToString() }), EventLogEntryType.Error);
                  
this.status.currentState = num1;
            }

      }

}


 

Note:
1. STOP_PENDING is set with checkPoint and waitHint both set to 0.(This looks strange!)
2. OnStop is called and then STATUS_STOPPED is set.
3. All exception is caught, except StackOverflowException, OutOfMemoryException, ThreadAbortException.
4. Stop operation success/failure is automatically logged.

Misc info:
1. OnStart is invoked in a background threadpool thread by ThreadPool.QueueUserWorkItem While OnStop/OnPause are invoked with delegate BeginInvoke, which runs in another background thread. So they are all run in different threads, not the main thread.
2. OnContinue, OnShutdown and OnCustomCommand are all called directly by *HandlerEx*, so they are all in the main thread.