I have a wierd problem with threading in an ASP.NET application. For some reason, when I run the code in the request thread, everything works as expected. But when I run it in a separate thread, nothing happens.
This is verified by calling the below handler with the three flags "on", "off" and "larma" respectively - in the two first cases everything works, but in the latter nothing happens.
What am I doing wrong here?
In the web project I have a generic handler with the following code:
If task = "on" Then
Alarm.StartaLarm(personId)
context.Response.Write("Larmet är PÅ")
ElseIf task = "off" Then
Alarm.StoppaLarm(personId)
context.Response.Write("Larmet är AV")
ElseIf task = "larma" Then
Alarm.Larma(personId)
context.Response.Write("Larmar... (stängs av automagiskt)")
Else
context.Response.Write("inget hände - task: " & task)
End If
The Alarm
class has the following methods:
Public Shared Sub Larma(ByVal personId As Integer)
Dim thread As New System.Threading.Thread(New ParameterizedThreadStart(AddressOf Larma_Thread))
thread.Start(personId)
End Sub
Private Shared Sub Larma_Thread(ByVal personId As Integer)
StartaLarm(personId)
Thread.Sleep(1000 * 30)
StoppaLarm(personId)
End Sub
Public Shared Sub StartaLarm(ByVal personId As Integer)
SandSMS(True, personId)
End Sub
Public Shared Sub StoppaLarm(ByVal personId As Integer)
SandSMS(False, personId)
End Sub
Public Shared Sub SandSMS(ByVal setOn As Boolean, ByVal personId As Integer)
...
End Sub
UPDATE/CLARIFICATION: I still get the expected response to the client - no error messages - when calling the threaded version.
I also included a forgotten method in the code above.
Update 2: @Henk, Unfortunately I don't have the ability to debug, because this problem arises only on our sharp server, which doesn't have Visual Studio installed and doesn't allow remote debugging.
However, the SendSMS
method sends text messages to my phone, and both the text message web service and my phone agrees that the messages are sent when calling "on" or "off", but not when calling "larma".
Since I know that the entire chain Handler->StartaLarm
->SandSMS(True/False)
works for "on" and "off", I must assume that the failure occurs somewhere in Handler->Larma
->Larma_Thread
, and thus is a threading issue.
Update 3: @Vadmyst, after converting your code to VB.NET (which is not my favourite of the two either, but this project requires it...) and modifying it to compile, I arrived at the following (although I'm not 100% certain it still means the same thing...):
ThreadPool.QueueUserWorkItem(New WaitCallback(Function(p As Integer) Larma_Thread(p)))
No success - I have the same results as above... =(