ThreadStateException when show the OpenFileDialog in the windowsservice control form

  • Thread starter Thread starter jcvoon
  • Start date Start date
J

jcvoon

Hi all:

In my windows services project, I add a windows form to the project
that act as the service control monitor, the form (frmInvestorProfile)
has a method to launch the OpenFileDialog, when run in the IDE it will
raise the following exception

ThreadStateException: Current thread must be set to single thread
apartment (STA) mode before OLE calls can be made. Ensure that your
Main function has STAThreadAttribute marked on it. This exception is
only raised if a debugger is attached to the process.

Here is the entry point of the service:

<MTAThread()> _
Shared Sub Main(ByVal args() As String)
If args.Length > 0 Then
If args(0).ToLower = "/i" Then
InstallService()
ElseIf args(0).ToLower = "/u" Then
UnInstallService()
End If
Else
Dim svc As ServiceController = Nothing

For Each itm As ServiceController In
ServiceController.GetServices
If itm.ServiceName = svcInstaller.SERVICE_NAME Then
svc = itm
Exit For
End If
Next

If svc Is Nothing OrElse svc.Status =
ServiceControllerStatus.Running Then
Application.Run(New frmInvestorProfile)
Else
If svc.Status <> ServiceControllerStatus.Running Then
Dim ServicesToRun() As
System.ServiceProcess.ServiceBase

ServicesToRun = New System.ServiceProcess.ServiceBase()
{New svcUpdateDailyNAV}

System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End If
End If
End If
End Sub

My Questions are:

1. If running in WinXP (outside the IDE) the service control monitor
form can show the OpenFileDialog, but in Vista it will hang. I
remember it work on Vista before, but after install the VS2008 and
couples of Vista update (I'm not sure it is cause by these reason) it
no longer work.

2. By default VS2005 generate the service entry point using
<MTAThread()> is it ok to change it to <STAThread> ?

Thanks
JCVoon
 
Back
Top