473,388 Members | 1,220 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Aborting a worker thread with pending IO: safe handle...disposed e

I read from a serialport using a worker thread. Because the worker thread t
does not loop often, I cannot wait to terminate the worker thread using a
boolean in the While condition.

So I have a StopReader() method that simply aborts the worker thread (is
there a better way for the above situation?).

The StopReader creates an ObjectDisposedException when calling t.Abort(). WHY?

Public Sub StopReader()
'stop the thread running the reader code and wait for the stop to
complete
Try
If Not Me.stoppedReading Then
If t.IsAlive AndAlso t IsNot Thread.CurrentThread Then
t.Abort()
'=THIS Abort() CREATES "OBJECT DISPOSED EXCEPTION - Safe handle has been
disposed"
t.Join()
End If
End If
Catch ex As ThreadStateException
Console.WriteLine("StopReader: ThreadStateException")
Catch ex As Exception
Console.WriteLine("StopReader: " & ex.message)
Finally
Me.stoppedReading = True 'flag that we stopped the reader
worker already
End Try
End Sub

Fine, so I include the lines:
Catch ex As ObjectDisposedException
Console.WriteLine("StopReader: ObjectDisposedException")
however the messages reappears and the catch doesn't work.
Here is the complete code:

Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class SerialPortReader
Implements IDisposable

Private disposedValue As Boolean = False ' To detect redundant
calls
Private stoppedReading As Boolean = False ' false = reader is
working
Dim myPort As SerialPort
Dim t As Thread 'worker thread for reader
Public Sub New()
Try
'create, configure and open a serial port
myPort = New SerialPort("COM4")
With myPort
.BaudRate = 9600
.DataBits = 8
.Parity = Parity.None
.StopBits = StopBits.One
.Handshake = Handshake.None
.DtrEnable = True
.Encoding = System.Text.Encoding.UTF8
End With
myPort.Open()
'delete old data
myPort.DiscardOutBuffer()
myPort.DiscardInBuffer()

'Catch ex As UnauthorizedAccessException
'this happens sometimes and is a confirmed bug (not an issue
here).
Catch ex As Exception
Console.WriteLine("Constructor: Thread abort exception.")
Finally

End Try
End Sub

Public Sub StartReader()
'set up a worker thread to read from the serial port
t = New Thread(AddressOf ReceiveWorker)
t.Start()
End Sub

Public Sub StopReader()
'stop the thread running the reader code and wait for the stop to
complete
Try
If Not Me.stoppedReading Then
If t.IsAlive AndAlso t IsNot Thread.CurrentThread Then
t.Abort() 'THIS CREATES "OBJECT DISPOSED EXCEPTION -
Safe handle has been disposed"
t.Join()
End If
End If
Catch ex As ObjectDisposedException 'doesn't catch the exception
Console.WriteLine("StopReader: ObjectDisposedException")
Catch ex As ThreadStateException
Console.WriteLine("StopReader: ThreadStateException")
Catch ex As Exception
Console.WriteLine("StopReader: " & ex.message)
Finally
Me.stoppedReading = True 'flag that we stopped the reader
worker already
End Try
End Sub

Public Sub ReceiveWorker()
'loop endlessly reading bytes from serial port
Dim myByte As Byte
Try
While (True)
myByte = CType(myPort.ReadByte, Byte) 'read
transparently from serial port
'... process received byte
End While
Catch ex As ThreadAbortException
Console.WriteLine("ReceiveWorker: Thread abort exception.")
Catch ex As Exception
Console.WriteLine("ReceiveWorker: other exception.")
Finally
End Try
End Sub

#Region " IDisposable Support "
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free managed resources when explicitly called
If Not IsNothing(myPort) Then
If Not Me.stoppedReading Then StopReader()
myPort.Dispose()
End If
End If

' TODO: free shared unmanaged resources
End If
Me.disposedValue = True
End Sub
' This code added by Visual Basic to correctly implement the disposable
pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal
disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region

End Class
Thank you very much. herbert
Jan 22 '07 #1
0 2409

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can...
1
by: johnny | last post by:
In a multi-threaded application, say a worker thread makes an asynchronous call and specifies a callback method. But before the callback is executed, the thread is aborted by its creator. What is...
5
by: Stephen Lamb | last post by:
I have a background worker thread which I start from a form's HandleCreated event that makes calls back to the form using Invoke. During shutdown the form is disposed and the background worker...
1
by: Robin Tucker | last post by:
Hi there, I have a "worker thread", which can perform one of many tasks, including fetching and sending data blobs to a database, load files etc. Now, a progress dialog is displayed while the...
1
by: Chris Morse | last post by:
WARNING: Verbosity: skip to the very bottom paragraph for succinct version of my question.) Hi- I can't seem to find an answer to this. I am playing around with a variation of the ".NET...
7
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have...
2
by: semedao | last post by:
Hi , someone know the reason and how to handle it? thanks
16
by: Paul Schwann | last post by:
Hi group, I am relatively new to C# (although I have a lot of programming excperience in other languages like Java and C). Currently I am searching for a solution to this problem: Suppose you...
1
by: nicerun | last post by:
I'm using the Application_Start event at Global.asax.cs to invoke thread that do some job. I know that Application_Start event occurs when the very first request to Web Application received. -...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.