2010-10-25 40 views
5

Tôi đang sử dụng đoạn mã sau để dừng dịch vụ. Tuy nhiên, cả hai câu lệnh Console.Writeline cho biết dịch vụ đang chạy. Tại sao dịch vụ không dừng lại?Dịch vụ Windows sẽ không dừng/bắt đầu

class Program 
{ 
    static void Main(string[] args) 
    { 
     string serviceName = "DummyService"; 
     string username = ".\\Service_Test2"; 
     string password = "Password1"; 

     ServiceController sc = new ServiceController(serviceName); 

     Console.WriteLine(sc.Status.ToString()); 

     if (sc.Status == ServiceControllerStatus.Running) 
     { 
      sc.Stop(); 
     } 

     Console.WriteLine(sc.Status.ToString()); 
    } 
} 
+0

Nơi nào bạn sử dụng tên đăng nhập và mật khẩu ?? – Aliostad

+0

Tôi sử dụng nó tiếp tục trong mã mà tôi thay đổi tài khoản và mật khẩu liên kết với dịch vụ. – xbonez

Trả lời

5

Bạn cần gọi số sc.Refresh() để làm mới trạng thái. Xem http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.stop.aspx để biết thêm thông tin.

Ngoài ra, có thể mất một chút thời gian để dịch vụ dừng lại. Nếu phương thức trả về ngay lập tức, nó có thể hữu ích để thay đổi shutdown của bạn vào một cái gì đó như thế này:

// Maximum of 30 seconds. 

for (int i = 0; i < 30; i++) 
{ 
    sc.Refresh(); 

    if (sc.Status.Equals(ServiceControllerStatus.Stopped)) 
     break; 

    System.Threading.Thread.Sleep(1000); 
} 
+0

hoạt động. Cảm ơn nhiều! – xbonez

1

thử gọi:

sc.Refresh(); 

trước khi cuộc gọi của bạn để Status.

2

Gọi sc.Refresh() trước khi kiểm tra trạng thái. Nó cũng có thể mất một thời gian để dừng lại.

0

Bạn có quyền chính xác để dừng/bắt đầu dịch vụ không?

Bạn đang chạy ứng dụng bảng điều khiển của tài khoản nào? Quyền quản trị?

Bạn đã thử sc.WaitForStatus chưa? Có thể dịch vụ đang dừng nhưng không phải lúc bạn đến được văn bản của bạn.

1

Tôi tin rằng bạn nên sử dụng sc.stop và sau đó làm mới http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.refresh(VS.80).aspx

// If it is started (running, paused, etc), stop the service. 
// If it is stopped, start the service. 
ServiceController sc = new ServiceController("Telnet"); 
Console.WriteLine("The Telnet service status is currently set to {0}", 
        sc.Status.ToString()); 

if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || 
    (sc.Status.Equals(ServiceControllerStatus.StopPending))) 
{ 
    // Start the service if the current status is stopped. 

    Console.WriteLine("Starting the Telnet service..."); 
    sc.Start(); 
} 
else 
{ 
    // Stop the service if its status is not set to "Stopped". 

    Console.WriteLine("Stopping the Telnet service..."); 
    sc.Stop(); 
} 

// Refresh and display the current service status. 
sc.Refresh(); 
Console.WriteLine("The Telnet service status is now set to {0}.", 
        sc.Status.ToString()); 
1

Hãy thử như sau:

while (sc.Status != ServiceControllerStatus.Stopped) 
{ 
    Thread.Sleep(1000); 
    sc.Refresh(); 
} 
Các vấn đề liên quan