Thread safety questions.

  • Thread starter Thread starter Frank Rizzo
  • Start date Start date
F

Frank Rizzo

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.                  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.                  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.                  Is this type of code safe?
4.                  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()
            oThread = New Thread(AddressOf StartListening)
            oThread.Name = “BOB”
            oThread.Start()
      End Sub
 
      Private Shared Sub StartListening()
            ‘blocking call
            Do
            If IsDataAvailable() Then
                  RaiseEvent DataArrived()
            End If
            Loop
      End Sub
End Class
 
Public Class Form1()
      ‘The Application starts here.
      Shared Sub Main()
            Thread.CurrentThread.Name = “MAIN”
            AddHandler Listener.DataArrived, AddressOf HandleData
      End Sub
 
      Private Sub HandleData()
            ‘lengthy database operation
      End Sub
End Class
 
'///Thank you.    
 
Back
Top