Re: Killing a blocking thread ?
- From: "Dick Grier" <dick_grierNOSPAM@xxxxxxx>
- Date: Fri, 17 Jun 2005 11:57:53 -0600
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.
.
- Follow-Ups:
- Re: Killing a blocking thread ?
- From: ManniAT
- Re: Killing a blocking thread ?
- References:
- Killing a blocking thread ?
- From: dahwoud
- Killing a blocking thread ?
- Prev by Date: Re: Killing a blocking thread ?
- Next by Date: Landscape mode questions
- Previous by thread: Re: Killing a blocking thread ?
- Next by thread: Re: Killing a blocking thread ?
- Index(es):
Relevant Pages
|