I am creating a Windows Service in VB.NET that will loop over a set of functions indefinitely, so threading is necessary. You can't just run your loop in OnStart()
; it has to return to the Service Controller.
My program completely crashes after New DataContext
with no exceptions or anything.
I have removed a lot of code that seems irrelevant to me, so that you can see the main problem code better. I have removed all Try
blocks and changed my Meter
types to Object
types, so you can copy and paste mostly working code.
I know this is a problem with DataContext and threading that I don't understand. Here's a summary of MultiThreading and DataContext concerns. What specifically am I doing wrong?
Public Class Molly
Dim stopping As Boolean = False
Dim stoppedEvent As Threading.ManualResetEvent
Protected Overrides Sub OnStart(ByVal args() As String)
'vv~~~~ If these two are uncommented, my code fails at an indeterminate place AFTER the New ConfigInterpreter below.
'Dim Example1 As New LocalDBDataContext
'Dim Example2 As New ConfigInterpreter
Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf ThreadWorker))
End Sub
Protected Overrides Sub OnStop()
stopping = True
stoppedEvent.WaitOne()
End Sub
Private Sub ThreadWorker()
Dim MyCI As New ConfigInterpreter '<~~~~ 'My program fails here every time,
'unless the two lines above are uncommented,
'then it fails at a random point after this.
Dim ListOfMeters as List(Of Meter) = MyCI.CompileListOfMeters()
While stopping = False
For Each mtr In ListOfMeters()
mtr.Read()
Next
Threading.Thread.Sleep(My.Settings.CheckIntervalMS)
End While
stoppedEvent.Set()
End Sub
End Class 'Molly
Public Class ConfigInterpreter
Public Sub New()
Try
Dim LocalDB As New LocalDBDataContext '<~~~~~~~ My program typically crashes here.
Catch ex As Exception '<~~~~ No exception is thrown.
End Try
End Sub
Public Function CompileListOfMeters() As List(Of Object)
Dim LocalDB As New LocalDBDataContext
Dim qMeters As IQueryable(Of tblMeter) = From ff In LocalDB.tblMeters
Select ff
Dim ReturnList As New List(Of Object)
For Each mtr In qMeters
ReturnList.Add(mtr)
Next
Return ReturnList
End Function
End Class 'ConfigInterpreter