473,728 Members | 1,443 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

windows services in .net, auto-restarting?

Hi...

Following the samples online, we implemented a windows service in .Net.
Like most services, there's a worker thread actually doing stuff in the
background. The problem we've run into is how to get the service to exit
when the worker thread has a fatal error *and* get the SCM to invoke the
auto-restart configuration?

The worker thread can error out while the parent thread in the server
process chugs along. We can set the exit code for the service in the worker
thread and then a) call this.Stop() or b) instantiate a ServiceControll er,
look ourselves up and call Stop(), or c) pull in the win32 dll and make an
unmanaged call to invoke stop. We can get the service to stop, but the
auto-restart configuration doesn't seem to kick in.

Reading old NT/Windows Services docs from win32, there is a line saying that
restart actions are taken *if the SCM wasn't called to Stop() the service*
i.e. only if the process dies a natural death.

So how does one get a .Net windows service just to die when the worker
thread dies?

Thanks
Mark

Feb 26 '07 #1
4 8830
Hi Mark,

Based on my understanding, you wanted to allow the service to leverage the
auto-restarting configuration while exceptions are generated in the
background worker thread. If I have misunderstood you, please feel free to
tell me, thanks.

Do you use .Net1.1 or .Net2.0 Windows Service? Do you catch the crash
exception in your thread proc? Based on my test in a VS2005 service with
auto-restarting configuration, if there is any unhandled exception
generated in the worker thread(without catching), the service process will
terminate and after 1 minite, the SCM will try to restart it again. My test
code is very simple, listed below:

private void ThreadProc()
{
throw new Exception("abc" );
}

protected override void OnStart(string[] args)
{
System.Threadin g.Thread t = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(T hreadProc));
t.Start();
}

Based on my experience, the SCM will take action on the auto-restarting
feature if the service fails. A service fails if its process dies without
the service setting its state to SERVICE_STOPPED . This is the key point.

If the exception is not caught in the ThreadProc, it will certainly crash
the service process without setting status to SERVICE_STOPPED . So the
auto-restarting will take effect.

If you have caught the exception, the Stop() method will not take effect in
our scenario. This is because Stop() method internally calls DeferredStop()
method which uses SetServiceStatu s with setting SERVICE_STOPPED (Note
SERVICE_STOPPED is of value 1 in const):

public void Stop()
{
this.DeferredSt op();
}

private unsafe void DeferredStop()
{
fixed (NativeMethods. SERVICE_STATUS* service_statusR ef1 =
&this.status )
{
int num1 = this.status.cur rentState;
this.status.che ckPoint = 0;
this.status.wai tHint = 0;
this.status.cur rentState = 3;
NativeMethods.S etServiceStatus (this.statusHan dle,
service_statusR ef1);
try
{
this.OnStop();
this.WriteEvent LogEntry(Res.Ge tString("StopSu ccessful"));
this.status.cur rentState = 1;//This is SERVICE_STOPPED
NativeMethods.S etServiceStatus (this.statusHan dle,
service_statusR ef1);
....
}
catch (Exception exception2)
{
....
}
}
}
Also, the service main thread ServiceMainCall back will also call
SetServiceStatu s with SERVICE_STOPPED . So if the main thread dies normally
or Stop() method is called, the service is recognized as exiting without
failure.

So, to achieve your requirement, we can not allow the main thread to exit
normally, one workaround is catching the exception in ThreadProc and does
the cleanup and save work in the catch handler. Finally, you may invoke
"throw;" keyword again to rethrow the exception. This will force the
service to die as failure, which allow the SCM to auto-restart the service
based on configuration.

Hope it helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 27 '07 #2
Hi Jeffrey...

A couple of us spent a long time googling around on the subject yesterday
and found some of your other posts on other groups (there isn't a clear
favorite group for this kind of question from the titles).

We've got a service using .Net 2.0. At first, the worker thread caught
exceptions and quietly exited which was not the optimal solution since that
left the process alive doing no work. Our next attempt was calling the SCM
via the native method to stop the service from the worker thread. But then
we found that the auto restart didn't kick in. Tried the same thing with
Stop(), creating the ServiceControll er object and stopping through that, etc.
As you say, the net result was that the SCM considered it a clean stop no
matter what we set the exit code to.

I thought one of the other guys tried throwing an uncaught exception from
the worker thread without success. Ultimately, we settled on
Environment.Exi t() from the worker thread; that seemed to do the trick. As
long as we aren't hosting multiple services in the process, it seemed to fit
the bill.

Thanks
Mark
""Jeffrey Tan[MSFT]"" wrote:
Hi Mark,

Based on my understanding, you wanted to allow the service to leverage the
auto-restarting configuration while exceptions are generated in the
background worker thread. If I have misunderstood you, please feel free to
tell me, thanks.

Do you use .Net1.1 or .Net2.0 Windows Service? Do you catch the crash
exception in your thread proc? Based on my test in a VS2005 service with
auto-restarting configuration, if there is any unhandled exception
generated in the worker thread(without catching), the service process will
terminate and after 1 minite, the SCM will try to restart it again. My test
code is very simple, listed below:

private void ThreadProc()
{
throw new Exception("abc" );
}

protected override void OnStart(string[] args)
{
System.Threadin g.Thread t = new System.Threadin g.Thread(new
System.Threadin g.ThreadStart(T hreadProc));
t.Start();
}

Based on my experience, the SCM will take action on the auto-restarting
feature if the service fails. A service fails if its process dies without
the service setting its state to SERVICE_STOPPED . This is the key point.

If the exception is not caught in the ThreadProc, it will certainly crash
the service process without setting status to SERVICE_STOPPED . So the
auto-restarting will take effect.

If you have caught the exception, the Stop() method will not take effect in
our scenario. This is because Stop() method internally calls DeferredStop()
method which uses SetServiceStatu s with setting SERVICE_STOPPED (Note
SERVICE_STOPPED is of value 1 in const):

public void Stop()
{
this.DeferredSt op();
}

private unsafe void DeferredStop()
{
fixed (NativeMethods. SERVICE_STATUS* service_statusR ef1 =
&this.status )
{
int num1 = this.status.cur rentState;
this.status.che ckPoint = 0;
this.status.wai tHint = 0;
this.status.cur rentState = 3;
NativeMethods.S etServiceStatus (this.statusHan dle,
service_statusR ef1);
try
{
this.OnStop();
this.WriteEvent LogEntry(Res.Ge tString("StopSu ccessful"));
this.status.cur rentState = 1;//This is SERVICE_STOPPED
NativeMethods.S etServiceStatus (this.statusHan dle,
service_statusR ef1);
....
}
catch (Exception exception2)
{
....
}
}
}
Also, the service main thread ServiceMainCall back will also call
SetServiceStatu s with SERVICE_STOPPED . So if the main thread dies normally
or Stop() method is called, the service is recognized as exiting without
failure.

So, to achieve your requirement, we can not allow the main thread to exit
normally, one workaround is catching the exception in ThreadProc and does
the cleanup and save work in the catch handler. Finally, you may invoke
"throw;" keyword again to rethrow the exception. This will force the
service to die as failure, which allow the SCM to auto-restart the service
based on configuration.

Hope it helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 27 '07 #3
Hi Mark,

Thanks for your detailed information. It really makes the problem much
clear.

Yes, Environment.Exi t() method immediately transfers into the CLR and will
terminate the entire process and give the underlying operating system the
specified exit code, so it will not allow the main service thread to invoke
SetServiceStatu s with SERVICE_STOPPED .

This should be a reliable solution for single-service application, and it
is more graceful and readable than my recommendation of rethowing the
unhandled exception.

Thanks for your sharing.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Feb 28 '07 #4
Hi Mark,

For your information:

Based on my recently reading to the service model on Vista. There is a
change to the service failure recovery model: a service doesn't have to
crash to have the SCM initiate a failure action.

Basically, a service can handle any unhandled exception and set
FailureActionsO nNonCrashFailur es to 1 to enable a service to notify the SCM
to initiate failure actions:
"A service notifies the SCM to queue a failure action by entering the
SERVICE_STOPPED state and setting SetServiceExitC ode function's
dwWin32ExitCode parameter to anything other than ERROR_SUCCESS."

However, I do not think .Net has exposed any class to leverage this new
Vista service model, so we still have to p/invoke to get it work.

Please refer to the "Failure Detection and Recovery" section in the page
below for the details:
"Services in Windows Vista"
http://www.microsoft.com/whdc/system..._Services.mspx

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Mar 1 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1746
by: Earl Eiland | last post by:
How does one make a Python program auto-execute in Windows? Earl
1
1791
by: Greg | last post by:
I have two classes (thus, two services) in one Windows Service executable. Each properly inherits from System.Process.ServiceBase, and I have a ServiceInstaller for each service, and one ServiceProcessInstaller for the entire executable, per the documentation. I can compile, and one service starts fine (the original one), but I can't start the service I just added, and I get this error: "Could not start the MyService service on Local...
1
258
by: Girish | last post by:
Im looking for information on how to build a windows service (not web service) on a .net enabled platform. Now, ive had some experience building services using vc++ 6.0 - and I can tell you its not straightforward. Now, I tried to examine the code that was auto generated when you create a new windows service project in vs.net 2003 (C#). I could not see any code for 1) Installing, uninstalling services. How can this be done in the .net...
2
21910
by: Mark | last post by:
I created an extremely simple windows service that only writes to the EventLogs on Stop and Pause. I installed it using the InstallUtil.exe program, the output of which is below. It appears to be successful. I'm now ready to start my service (I think) but the NET START command does not appear to indicate that the service is available to be run. The output for NET START is below as well. The Services list in the W2K administrator...
2
2056
by: Jeffrey Tate via DotNetMonster.com | last post by:
The error is: The proxy settings on this computer are not configured correctly for Web discovery. MSDN states that this is caused by: This error appears in the Add Web Reference dialog box if you are developing on a machine that is behind a firewall and a proxy server has not been explicitly specified for Internet Explorer connections. You need to explicitly specify the address and port of the proxy server on your network in order to make...
3
6507
by: Matt D | last post by:
I've got two web services that use the same data types and that clients will have to consume. I read the msdn article on sharing types (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnservice/html/service07162002.asp) but I don't want clients to have to add two web references and then manually have to edit the proxy classes. After doing some searching I found that putting references to multiple web services in a .disco...
3
7488
by: Chris Paul | last post by:
I'm having trouble with PHP & PostgreSQL/OpenLDAP/Apache on Windows. I've set this up countless times on BSD (piece of cake) but I'm trying to do this on Windows now so that my developer can work on her local machine. Everything looks pretty good. OpenLDAP/cygwin works great. PostgreSQL works great. Apache runs. PHP runs. But when I try to connect to my PostgreSQL server using PHPPgAdmin, I
8
6771
by: Todd Jaspers | last post by:
Hey guys, I've written a fairly simple Windows C# Application using Visual Studio 2005. I have to manually run it, but I would prefer to have it run on it's own, as if it was a Windows NT Service. I am a Delphi convert (still use it for some jobs). When developing in Delphi, I would write a console application that would basically run on it's own. In order for me to register it as a Windows NT Service, I seem to recall that I would do...
0
6122
AmberJain
by: AmberJain | last post by:
Windows Autorun FAQs: Overview NOTE- This complete article on "Windows Autorun FAQs" applies theoretically to all Windows NT-based OSes till Windows Vista (and probably Vista's successors too). Much of the contents of this article are tested on Windows XP professional SP2 by the author. Some instances of this article may be altogether different/missing on Windows Vista, XP and other Windows NT systems, but I have tried to write a...
0
30237
AmberJain
by: AmberJain | last post by:
Windows Autorun FAQs: List of autostart locations Linked from the Original article- "Windows Autorun FAQs: Description". Que: Can you list all the autostart locations for windows? Ans: Here is a comprehensive list of all autostart locations for Windows OSes: NOTE : These are some abbreviations used in this list. Please note them carefully: HKCU = HKEY_CURRENT_USER HKLM = HKEY_LOCAL_MACHINE
0
8756
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9416
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9270
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9194
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9126
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8123
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6012
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3232
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2159
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.