(跪求大虾)多线程里停止服务出现Runtime Error
1. 自己的测试环境是WindowXp 32bit, .net framework2.0
2. 服务器的测试环境是Window2003 64bit, .net framework2.0
3. 我用SC命令创建了服务(S69Abathcs)
4. 我试图让该服务做完业务逻辑之后,把该服务(自己)停止
5. 再1的情况下没有问题,在2的情况下,该服务虽然停止,但是最后出现了错误。
6. 错误内容:
EventType clr20r3, P1 s69abatchs.exe,..., system.serviceprocess,P5 2.0.0.0,P6....,system.invalidoperationexception,P10 NIL.(...内容是一些内存地址)
7.代码如下:(注意红色地方)
Public Class Class1
Inherits System.ServiceProcess.ServiceBase
Private components As System.ComponentModel.IContainer
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If (disposing = True) Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
<MTAThread()> Shared Sub Main()
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Class1()}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
Protected Overrides Sub OnStop()
MyBase.OnStop()
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
Dim l_thr As New Thread(AddressOf WinProc)
Try
l_thr.Start()
Catch ex As Exception
Throw ex
End Try
End Sub
Private Sub WinProc()
Dim objServiceSearcher As New System.Management.ManagementObjectSearcher( _
"\\localhost\root\CIMV2", _
"SELECT * FROM Win32_Service Where Name = '" & Me.ServiceName & "'")
Do
For Each objService As System.Management.ManagementObject In objServiceSearcher.Get()
If objService("Name").Equals(Me.ServiceName) And _
objService("State").Equals("Running") Then
Dim sc As ServiceController = New ServiceController(Me.ServiceName)
Thread.Sleep(15000)
If (sc.Status = ServiceControllerStatus.Running) Then
sc.Stop() //只要执行该方法,错误就出现。
//个人认为是不安全线程引起的,不知道对否。如何解决这个问题?
End If
Exit Do
End If
Next
Loop
End Sub
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.ServiceName = "S69Abatchs"
End Sub
End Class