2009-05-19 14 views
5
ServiceController serviceController = new ServiceController(someService); 
serviceController.Stop(); 
serviceController.WaitForStopped(); 
DoSomething(); 

कुछ सेवा एक SQL सर्वर फ़ाइल पर काम करती है। DoSomething() उस SQL ​​फ़ाइल की प्रतिलिपि बनाना चाहता है। अगर कुछ सेवा पूरी तरह से बंद नहीं होती है तो यह एक त्रुटि फेंक देगी क्योंकि डेटाबेस फ़ाइल अभी भी बंद है। उपर्युक्त कोड में, मुझे WaitForStopped() विधि से पहले मिलता है और फिर भी सेवा DoSomething() के बाद तक डेटाबेस फ़ाइल को रिलीज़ नहीं करती है, इस प्रकार मुझे एक त्रुटि मिलती है।सेवा नियंत्रक के बाद सेवा पूरी तरह से बंद नहीं हुई है। रोकें()

कुछ और जांच करने से पहले, मुझे लगता है कि DoSomething विधि कॉल से पहले मुझे लगता है कि सेवा नियंत्रक स्थिति एक रोका दिखाती है और फिर भी कुछ ProcMon लॉग को देखकर सर्विस को डेटाबेस फ़ाइल को रिलीज़ करने के बाद डेटाबेस फ़ाइल को रिलीज़ करता है।

इसके अलावा, अगर मैं थ्रेड डालता हूं। WaitForStopped और DoSomething विधि के बीच सोएं ... 5 सेकंड, डेटाबेस फ़ाइल जारी की जाती है और सब ठीक है। निश्चित रूप से मैं समाधान की तलाश नहीं कर रहा हूं।

कोई विचार?

उत्तर

3

सर्विस कंट्रोलर। WaitForStopped()/WaitForStatus() सेवा कार्यान्वयन के दावों को बंद करने के बाद वापस आ जाएगा। यह जरूरी नहीं है कि प्रक्रिया ने अपने सभी संसाधनों को जारी कर दिया है और बाहर निकला है। मैंने एसक्यूएल सर्वर के अलावा अन्य डेटाबेस भी देखा है।

यदि आप वास्तव में सुनिश्चित करना चाहते हैं कि डेटाबेस पूरी तरह से और वास्तव में बंद हो गया है, तो आपको डेटाबेस के साथ इंटरफ़ेस करना होगा, प्रक्रिया आईडी को रोकना होगा और बाहर निकलने के लिए प्रतीक्षा करें, फ़ाइलों पर ताले के लिए प्रतीक्षा करें जारी किया गया, ...

+0

एचआरएम, यह जवाब क्यों है। हालांकि एक अच्छा कामकाज पर कोई विचार? – Dave

-4

पर्यावरण का उपयोग करने का प्रयास करें। एक्सिट (1);

+5

जबरन समाप्त एसक्यूएल सर्वर एक बहुत बुरा विचार है। –

0

मैंने इसे पहले देखा है जब मैंने एक ऐसी सेवा को रोक दिया जो किसी अन्य सेवा की निर्भरता थी, और दूसरी सेवा संसाधनों को पकड़ रही थी, मुझे यह भी पता नहीं था कि यह उपयोग कर रहा था। क्या आपको लगता है कि यह मामला हो सकता है? मुझे पता है कि एसक्यूएल में कुछ अलग-अलग घटक हैं, लेकिन मैंने यह नहीं देखा है कि इसमें कई सेवाएं हैं या नहीं।

शुभकामनाएं!

17

विंडोज सेवा प्रक्रियाओं के शीर्ष पर एक परत है; सेवा होने के लिए, एक आवेदन को सेवा नियंत्रण प्रबंधक से कनेक्ट होना चाहिए और यह घोषणा करना चाहिए कि कौन सी सेवाएं उपलब्ध हैं। यह कनेक्शन ADVAPI32.DLL लाइब्रेरी के भीतर संभाला जाता है। एक बार यह कनेक्शन स्थापित हो जाने पर, लाइब्रेरी सेवा नियंत्रण प्रबंधक से आदेशों के लिए प्रतीक्षा करने वाले थ्रेड को बनाए रखती है, जो तब मनमाने ढंग से सेवाओं को शुरू और बंद कर सकती है। मुझे विश्वास नहीं है कि आखिरी सेवा समाप्त होने पर प्रक्रिया से बाहर निकलने की आवश्यकता है। यद्यपि आमतौर पर ऐसा होता है, सेवा नियंत्रण प्रबंधक के साथ लिंक का अंत, जो अंतिम सेवा के बाद होता है "रोक" स्थिति में प्रवेश करता है, प्रक्रिया वास्तव में समाप्त होने से पहले महत्वपूर्ण हो सकती है, किसी भी संसाधन को जारी करना जो पहले से ही स्पष्ट रूप से रिलीज़ नहीं हुआ है ।

विंडोज सेवा एपीआई में कार्यक्षमता शामिल है जो आपको सेवा की मेजबानी की प्रक्रिया की प्रक्रिया आईडी प्राप्त करने देती है। एक ही प्रक्रिया के लिए कई सेवाओं की मेजबानी करना संभव है, और इसलिए जब आप जिस सेवा में रूचि रखते हैं, तो प्रक्रिया वास्तव में बाहर नहीं हो सकती है, लेकिन आपको SQL सर्वर से सुरक्षित होना चाहिए। दुर्भाग्यवश, .NET Framework इस कार्यक्षमता का खुलासा नहीं करता है। हालांकि, यह उस सेवा को हैंडल का खुलासा करता है जो यह एपीआई कॉल के लिए आंतरिक रूप से उपयोग करता है, और आप इसे अपने स्वयं के एपीआई कॉल करने के लिए उपयोग कर सकते हैं। पी/Invoke के कुछ के साथ, आप Windows सेवा प्रक्रिया की प्रक्रिया आईडी प्राप्त कर सकते हैं, और वहां से, बशर्ते आपके पास आवश्यक अनुमति हो, आप उस प्रक्रिया में एक हैंडल खोल सकते हैं जिसका उपयोग इसके लिए प्रतीक्षा करने के लिए किया जा सकता है बाहर जाएं।

कुछ इस तरह:

[DllImport("advapi32")] 
static extern bool QueryServiceStatusEx(IntPtr hService, int InfoLevel, ref SERVICE_STATUS_PROCESS lpBuffer, int cbBufSize, out int pcbBytesNeeded); 

const int SC_STATUS_PROCESS_INFO = 0; 

[StructLayout(LayoutKind.Sequential)] 
struct SERVICE_STATUS_PROCESS 
{ 
    public int dwServiceType; 
    public int dwCurrentState; 
    public int dwControlsAccepted; 
    public int dwWin32ExitCode; 
    public int dwServiceSpecificExitCode; 
    public int dwCheckPoint; 
    public int dwWaitHint; 
    public int dwProcessId; 
    public int dwServiceFlags; 
} 

const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; 

const int SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001; 

public static void StopServiceAndWaitForExit(string serviceName) 
{ 
    using (ServiceController controller = new ServiceController(serviceName)) 
    { 
    SERVICE_STATUS_PROCESS ssp = new SERVICE_STATUS_PROCESS(); 
    int ignored; 

    // Obtain information about the service, and specifically its hosting process, 
    // from the Service Control Manager. 
    if (!QueryServiceStatusEx(controller.ServiceHandle.DangerousGetHandle(), SC_STATUS_PROCESS_INFO, ref ssp, Marshal.SizeOf(ssp), out ignored)) 
     throw new Exception("Couldn't obtain service process information."); 

    // A few quick sanity checks that what the caller wants is *possible*. 
    if (ssp.dwServiceType != SERVICE_WIN32_OWN_PROCESS) 
     throw new Exception("Can't wait for the service's hosting process to exit because there may be multiple services in the process (dwServiceType is not SERVICE_WIN32_OWN_PROCESS"); 

    if ((ssp.dwServiceFlags & SERVICE_RUNS_IN_SYSTEM_PROCESS) != 0) 
     throw new Exception("Can't wait for the service's hosting process to exit because the hosting process is a critical system process that will not exit (SERVICE_RUNS_IN_SYSTEM_PROCESS flag set)"); 

    if (ssp.dwProcessId == 0) 
     throw new Exception("Can't wait for the service's hosting process to exit because the process ID is not known."); 

    // Note: It is possible for the next line to throw an ArgumentException if the 
    // Service Control Manager's information is out-of-date (e.g. due to the process 
    // having *just* been terminated in Task Manager) and the process does not really 
    // exist. This is a race condition. The exception is the desirable result in this 
    // case. 
    using (Process process = Process.GetProcessById(ssp.dwProcessId)) 
    { 
     // EDIT: There is no need for waiting in a separate thread, because MSDN says "The handles are valid until closed, even after the process or thread they represent has been terminated." (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684868%28v=vs.85%29.aspx), so to keep things in the same thread, the process HANDLE should be opened from the process id before the service is stopped, and the Wait should be done after that. 

     // Response to EDIT: What you report is true, but the problem is that the handle isn't actually opened by Process.GetProcessById. It's only opened within the .WaitForExit method, which won't return until the wait is complete. Thus, if we try the wait on the current therad, we can't actually do anything until it's done, and if we defer the check until after the process has completed, it won't be possible to obtain a handle to it any more. 

     // The actual wait, using process.WaitForExit, opens a handle with the SYNCHRONIZE 
     // permission only and closes the handle before returning. As long as that handle 
     // is open, the process can be monitored for termination, but if the process exits 
     // before the handle is opened, it is no longer possible to open a handle to the 
     // original process and, worse, though it exists only as a technicality, there is 
     // a race condition in that another process could pop up with the same process ID. 
     // As such, we definitely want the handle to be opened before we ask the service 
     // to close, but since the handle's lifetime is only that of the call to WaitForExit 
     // and while WaitForExit is blocking the thread we can't make calls into the SCM, 
     // it would appear to be necessary to perform the wait on a separate thread. 
     ProcessWaitForExitData threadData = new ProcessWaitForExitData(); 

     threadData.Process = process; 

     Thread processWaitForExitThread = new Thread(ProcessWaitForExitThreadProc); 

     processWaitForExitThread.IsBackground = Thread.CurrentThread.IsBackground; 
     processWaitForExitThread.Start(threadData); 

     // Now we ask the service to exit. 
     controller.Stop(); 

     // Instead of waiting until the *service* is in the "stopped" state, here we 
     // wait for its hosting process to go away. Of course, it's really that other 
     // thread waiting for the process to go away, and then we wait for the thread 
     // to go away. 
     lock (threadData.Sync) 
     while (!threadData.HasExited) 
      Monitor.Wait(threadData.Sync); 
    } 
    } 
} 

class ProcessWaitForExitData 
{ 
    public Process Process; 
    public volatile bool HasExited; 
    public object Sync = new object(); 
} 

static void ProcessWaitForExitThreadProc(object state) 
{ 
    ProcessWaitForExitData threadData = (ProcessWaitForExitData)state; 

    try 
    { 
    threadData.Process.WaitForExit(); 
    } 
    catch {} 
    finally 
    { 
    lock (threadData.Sync) 
    { 
     threadData.HasExited = true; 
     Monitor.PulseAll(threadData.Sync); 
    } 
    } 
} 
+0

पूरी तरह से काम करता है, बहुत बहुत धन्यवाद! –

1

मेरे मामले में मैं interops का इस्तेमाल किया है:

[StructLayout(LayoutKind.Sequential)] 
public struct SC_HANDLE__ 
{ 
    public int unused; 
} 

[Flags] 
public enum SERVICE_CONTROL : uint 
{ 
    STOP = 0x00000001, 
    PAUSE = 0x00000002, 
    CONTINUE = 0x00000003, 
    INTERROGATE = 0x00000004, 
    SHUTDOWN = 0x00000005, 
    PARAMCHANGE = 0x00000006, 
    NETBINDADD = 0x00000007, 
    NETBINDREMOVE = 0x00000008, 
    NETBINDENABLE = 0x00000009, 
    NETBINDDISABLE = 0x0000000A, 
    DEVICEEVENT = 0x0000000B, 
    HARDWAREPROFILECHANGE = 0x0000000C, 
    POWEREVENT = 0x0000000D, 
    SESSIONCHANGE = 0x0000000E 
} 

[StructLayout(LayoutKind.Sequential)] 
public struct SERVICE_STATUS 
{ 

    /// DWORD->unsigned int 
    public uint dwServiceType; 
    /// DWORD->unsigned int 
    public uint dwCurrentState; 
    /// DWORD->unsigned int 
    public uint dwControlsAccepted; 
    /// DWORD->unsigned int 
    public uint dwWin32ExitCode; 
    /// DWORD->unsigned int 
    public uint dwServiceSpecificExitCode; 
    /// DWORD->unsigned int 
    public uint dwCheckPoint; 
    /// DWORD->unsigned int 
    public uint dwWaitHint; 
} 

public class NativeMethods 
{ 
    public const int SC_MANAGER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED 
       | (SC_MANAGER_CONNECT 
       | (SC_MANAGER_CREATE_SERVICE 
       | (SC_MANAGER_ENUMERATE_SERVICE 
       | (SC_MANAGER_LOCK 
       | (SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG)))))); 

    /// STANDARD_RIGHTS_REQUIRED -> (0x000F0000L) 
    public const int STANDARD_RIGHTS_REQUIRED = 983040; 
    /// SC_MANAGER_CONNECT -> 0x0001 
    public const int SC_MANAGER_CONNECT = 1; 
    /// SC_MANAGER_CREATE_SERVICE -> 0x0002 
    public const int SC_MANAGER_CREATE_SERVICE = 2; 
    /// SC_MANAGER_ENUMERATE_SERVICE -> 0x0004 
    public const int SC_MANAGER_ENUMERATE_SERVICE = 4; 
    /// SC_MANAGER_LOCK -> 0x0008 
    public const int SC_MANAGER_LOCK = 8; 
    /// SC_MANAGER_QUERY_LOCK_STATUS -> 0x0010 
    public const int SC_MANAGER_QUERY_LOCK_STATUS = 16; 
    /// SC_MANAGER_MODIFY_BOOT_CONFIG -> 0x0020 
    public const int SC_MANAGER_MODIFY_BOOT_CONFIG = 32; 
    /// SERVICE_CONTROL_STOP -> 0x00000001 
    public const int SERVICE_CONTROL_STOP = 1; 
    /// SERVICE_QUERY_STATUS -> 0x0004 
    public const int SERVICE_QUERY_STATUS = 4; 
    public const int GENERIC_EXECUTE = 536870912; 
    /// SERVICE_RUNNING -> 0x00000004 
    public const int SERVICE_RUNNING = 4; 

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
    static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess); 

    [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW")] 
    public static extern IntPtr OpenSCManagerW(
     [In()] [MarshalAs(UnmanagedType.LPWStr)] string lpMachineName, 
     [In()] [MarshalAs(UnmanagedType.LPWStr)] string lpDatabaseName, 
     uint dwDesiredAccess); 

    [DllImport("advapi32.dll", SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus); 

    [DllImport("advapi32.dll", SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    public static extern bool CloseServiceHandle(IntPtr hSCObject); 

    [DllImport("advapi32.dll", EntryPoint = "QueryServiceStatus", CharSet = CharSet.Auto)] 
    public static extern bool QueryServiceStatus(IntPtr hService, ref SERVICE_STATUS dwServiceStatus); 

    [SecurityCritical] 
    [HandleProcessCorruptedStateExceptions] 
    public static void ServiceStop() 
    { 
     IntPtr manager = IntPtr.Zero; 
     IntPtr service = IntPtr.Zero; 
     SERVICE_STATUS status = new SERVICE_STATUS(); 

     if ((manager = OpenSCManagerW(null, null, SC_MANAGER_ALL_ACCESS)) != IntPtr.Zero) 
     { 
      if ((service = OpenService(manager, Resources.ServiceName, SC_MANAGER_ALL_ACCESS)) != IntPtr.Zero) 
      { 
       QueryServiceStatus(service, ref status); 
      } 

      if (status.dwCurrentState == SERVICE_RUNNING) 
      { 
       int i = 0; 
       //not the best way, but WaitStatus didnt work correctly. 
       while (i++ < 10 && status.dwCurrentState != SERVICE_CONTROL_STOP) 
       { 
        ControlService(service, SERVICE_CONTROL.STOP, ref status); 
        QueryServiceStatus(service, ref status); 
        Thread.Sleep(200); 
       } 

      } 
     } 


     if (manager != IntPtr.Zero) 
     { 
      var b = CloseServiceHandle(manager); 
     } 

     if (service != IntPtr.Zero) 
     { 
      var b = CloseServiceHandle(service); 
     } 
    } 
} 
संबंधित मुद्दे