Re: Killing a blocking thread ?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Hi,

IMO, you get much better performance if you DO NOT use blocking reads. What
I do is to create a thread that enters a loop to read. Monitor a flag
inside the loop, and exit from the thread when/if the flag is set. This
kills the thread. Here is the code that I use (VB, but C# would be
similar):

'The ReadTCP class wraps the Tcpclient class Read method with a worker
thread

'that provides a method to terminate the thread when the application closes.

Friend Class ReadTCP

Friend Reading As Boolean 'Field to signal the state of the object

Friend Client As TcpClient

Friend Event DataAvailable(ByVal Buffer() As Byte)

Private ReadThread As Thread

'Call Start to create a new worker thread.

Friend Sub Start()

ReadThread = New Thread(AddressOf ReadThreadProc)

Reading = True

ReadThread.Start()

End Sub

'This is the worker thread that polls the Tcpclient.GetStream.Read method.

Private Sub ReadThreadProc()

Dim Buffer() As Byte

With Client.GetStream

Do Until Reading = False

If .DataAvailable = True Then

Try

ReDim Buffer(READ_BUFFER_SIZE)

..Read(Buffer, 0, READ_BUFFER_SIZE)

RaiseEvent DataAvailable(Buffer)

Catch ex As Exception

End Try

End If

Thread.Sleep(1)

Loop

End With

End Sub

End Class

End Class

Dick
--
Richard Grier (Microsoft Visual Basic MVP)

See www.hardandsoftware.net for contact information.

Author of Visual Basic Programmer's Guide to Serial Communications, 4th
Edition ISBN 1-890422-28-2 (391 pages) published July 2004. See
www.mabry.com/vbpgser4 to order.


.



Relevant Pages

  • Re: VB project
    ... Generally I advise students to consult their instructor. ... going to your friend. ... Private Sub Form_Load ... Dim num() As Byte ...
    (microsoft.public.vb.general.discussion)
  • Inaccessable Radiant heating and plumbing problems
    ... A friend of mine has a large home built in 1950. ... The house has radiant heating with copper pipe buried in the concrete. ... water sprying out of the loop via a burst pipe under the concrete. ...
    (alt.home.repair)
  • Re: Was ist den mit friend los?
    ... > Jetzt habe ich mal mit einem UserControl in einem Exe-Projekt getestet. ... > Friend Property Get Test() As String ... > End Property ... > Private Sub UserControl_DblClick ...
    (microsoft.public.de.vb)
  • Re: How to Call (utilize) a Sub() in a Class DLL?
    ... so you want to declare it only once in the entire NET ... "Friend" is the middle path. ... Public Sub SetXLHwnd ...
    (microsoft.public.excel.programming)
  • Re: Dataview not updating Dataset
    ... adpGuest.Update(dsVIP, "Guest") ... because AcceptChanges consolidates changes in datatable thus should be ... > When I put the call to UpdateGuestTablein the dvGuest_ListChanged sub I ... > Friend adpGuest As OleDbDataAdapter ...
    (microsoft.public.dotnet.framework.adonet)