473,657 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Aborting a worker thread with pending IO: safe handle...dispos ed 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 ObjectDisposedE xception 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.stoppedReadi ng Then
If t.IsAlive AndAlso t IsNot Thread.CurrentT hread Then
t.Abort()
'=THIS Abort() CREATES "OBJECT DISPOSED EXCEPTION - Safe handle has been
disposed"
t.Join()
End If
End If
Catch ex As ThreadStateExce ption
Console.WriteLi ne("StopReader : ThreadStateExce ption")
Catch ex As Exception
Console.WriteLi ne("StopReader : " & ex.message)
Finally
Me.stoppedReadi ng = True 'flag that we stopped the reader
worker already
End Try
End Sub

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

Imports System.IO
Imports System.IO.Ports
Imports System.Threadin g

Public Class SerialPortReade r
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("COM 4")
With myPort
.BaudRate = 9600
.DataBits = 8
.Parity = Parity.None
.StopBits = StopBits.One
.Handshake = Handshake.None
.DtrEnable = True
.Encoding = System.Text.Enc oding.UTF8
End With
myPort.Open()
'delete old data
myPort.DiscardO utBuffer()
myPort.DiscardI nBuffer()

'Catch ex As UnauthorizedAcc essException
'this happens sometimes and is a confirmed bug (not an issue
here).
Catch ex As Exception
Console.WriteLi ne("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(AddressO f 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.stoppedReadi ng Then
If t.IsAlive AndAlso t IsNot Thread.CurrentT hread Then
t.Abort() 'THIS CREATES "OBJECT DISPOSED EXCEPTION -
Safe handle has been disposed"
t.Join()
End If
End If
Catch ex As ObjectDisposedE xception 'doesn't catch the exception
Console.WriteLi ne("StopReader : ObjectDisposedE xception")
Catch ex As ThreadStateExce ption
Console.WriteLi ne("StopReader : ThreadStateExce ption")
Catch ex As Exception
Console.WriteLi ne("StopReader : " & ex.message)
Finally
Me.stoppedReadi ng = 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.Re adByte, Byte) 'read
transparently from serial port
'... process received byte
End While
Catch ex As ThreadAbortExce ption
Console.WriteLi ne("ReceiveWork er: Thread abort exception.")
Catch ex As Exception
Console.WriteLi ne("ReceiveWork er: other exception.")
Finally
End Try
End Sub

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

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

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

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

Similar topics

0
375
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 fail if the event is emptied of all methods between the two statements, implying that some sort of synchronization between this and removals from EventName is needed. The other problem is that if an event with a set of delegates is in the process...
1
2615
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 the expected behavior for this scenario? Does the thread stay alive until the callback is executed? If an exception is thrown, can it be caught? I posted this message last week, but got no response. I am really hoping someone can help me with...
5
8103
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 thread is aborted by the system. How is one to keep the background thread from calling form.Invoke after the form's window handle has been destroyed? This is definitely happening in my application. I haven't read anything about this problem in...
1
1218
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 thread is performing these actions with a "cancel" button on it. My question is, at what point does the thread actually stop running after I have executed "Abort" in response to the user pressing cancel? Is it immediate? Or does the thread...
1
6276
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 Framework Developer's Guide" (in the MSDN docs) "Using an Asynchronous Server Socket" sample. As usual with docs like this, the example isn't very good. I had to
7
2683
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 a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
2
5174
by: semedao | last post by:
Hi , someone know the reason and how to handle it? thanks
16
8381
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 have 3 methods A, B and C. All of them shall be run threaded (I/O tasks) and one after another. I can create a thread and schedule one method just like:
1
3438
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. - Setting worker process count 1. Start | Programs | Administrative Tools | Internet Information Services 2. Right-click on the application pool, e.g. ‘DefaultAppPool’, and select ‘Properties’
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.