I have an app that listen to data on a certain resource. Data can come in on this resource any time, so I have to listen for it the entire time. I wanted to see if what I have is thread-safe and makes sense. Consider the code below. The app starts and creates code to handle an even from the Listener class. The listener class creates a new thread (will call it thread BOB) inside it that listens to data. When the data arrives, it is received on the BOB thread. Then an event is fired, which is then handled in the calling class (Form1 in this case). That is followed by a lengthy database operation. My questions are as follows:
1. &n bsp; When event is fired, and Form1.HandleData sub kicks in, is it received on the main application thread or the new BOB thread? If HandleData runs on the main thread, where, when and how is the event marshalled between threads?
2. &n bsp; When I run my lengthy database operation in HandleData, what is blocked? The main application thread or the new BOB thread? Also, will I be able to still receive data in my BOB thread, when the lengthy database operation is performed?
3. &n bsp; Is this type of code safe?
4. &n bsp; Is it good practice? If not, what are the alternatives?
Imports System.Threading
Public Class Listener
Public Shared Event DataArrived()
Private Shared oThread As Thread
Public Shared Sub Listen()
&n bsp; oThread = New Thread(AddressOf StartListening)
&n bsp; oThread.Name = “BOB”
&n bsp; oThread.Start()
End Sub
Private Shared Sub StartListening()
&n bsp; ‘blocking call
&n bsp; Do
&n bsp; If IsDataAvailable() Then
&n bsp; &nbs p; RaiseEvent DataArrived()
&n bsp; End If
&n bsp; Loop
End Sub
End Class
Public Class Form1()
‘The Application starts here.
Shared Sub Main()
&n bsp; Thread.CurrentThread.Name = “MAIN”
&n bsp; AddHandler Listener.DataArrived, AddressOf HandleData
End Sub
Private Sub HandleData()
&n bsp; ‘lengthy database operation
End Sub
End Class
'///Thank you.