Reputation: 788
I am working on a VB.Net project, and I want a fast and dirty way of having a second thread preform some function, then store some variable outcome to the session. Then I want to access that variable from the first thread (in the same session of course).
Here is an example of the code...
Button#1
Sub button_Click1(byVal sender As Object, ByVal e As Event Args)
textfield1.Visible = False
lable2.Visible = True
textfield2.Visible = True
button_Click2.Visible = True
Dim thread2 As New System.Threading.Thread(AddressOf foothread)
thread2.Start(textfield1.Text.ToString)
End Sub
Button#2
Sub button_Click2(byVal sender As Object, ByVal e As Event Args)
If(textfield2.Text = "is cool" And System.Web.HttpContext.Current.Session("myBool") = true) Then
lable2 = "You're right!"
else
lable2 = "???"
end If
Thread #2
Public Sub thread2(ByVal str1 As String)
If(srt1 = "Stack/Flow") Then
System.Web.HttpContext.Current.Session("myBool") = true
Else
System.Web.HttpContext.Current.Session("myBool") = false
End If
End Sub
Obviously this is not a real production example, I am running a lengthy query in the thread which will return my session variable (lengthy due to network traffic to that box)
Is this possible? Is there a better way? Will this even work? New to multithreaded applications.
Thanks!
Upvotes: 0
Views: 1208
Reputation: 700910
No, that doesn't work. The second thread doesn't have a HTTP context, only threads that run to handle requests have a HTTP context.
Youcan make a class for the method to run in the second thread, and add any input and output data as members in the class:
Public Class Thread2Class
Public Str1 As String
Public MyBool As Boolean
Public Sub Run()
If Str1 = "Stack/Flow" Then
MyBool = True
Else
MyBool = False
End If
End Sub
End Class
Create an instance of the class, set the input data, and start the thread:
Dim thread2 As New Thread2Class
thread2.Str1 = Lable1.Text.ToString
Dim thread2 As New System.Threading.Thread(AddressOf thread2.Run)
thread2.Start()
Keep the reference to the class, so that you can read the result from the member when the thread has finished:
Dim result As Boolean = thread2.MyBool
Upvotes: 1