When run via the Service Control Manager do Windows services need to assume that command processing methods (OnStart, OnStop, etc.) can be called on different threads with nothing ensuring that, e.g., assignments to members will be visible between methods?
public class MyService : ServiceBase {
private Object _foo;
protected override void OnStart(string[] args) {
_foo = new Object();
}
protected override void OnStop() {
if (_foo == null) {
throw new Exception("Assignment not visible"); // Can this happen?
}
_foo = null;
}
}
I can't find a guarantee that the exception in my example won't be thrown, but all of the examples I've found, including elsewhere on StackOverflow, seems to assume that, e.g., assignments to variables in OnStart() will always be visible in OnStop().
If no such guarantee is made by the SCM I do know how to ensure the assignment is visible (e.g. by adding a lock around all reads/writes in the service). I'm interested in whether or not such measures are necessary.
the example you gave can in did happen its just very very improbable ex:
[EDIT]: as referred in comment SCM prevents the OnStop from Running before the OnStart completes. this comment comes from my possible bad practice of exposing the start and stop wrappers as public.
if the stop event is called before the new finishes it can happen that the _foo is null;
and also _foo can be released in adder place in code so its a good practice to check first.