473,804 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Correct thread termination

Hi there,

Previously when handling the termination of threads I had just called the
abort method and caught it in a try catch block in the thread callback.
After recently learning that this was a bad way of handling thread
termination I am working on terminating threads by using ManualResetEven t's.

I have come up with the following code which appears to work very well (at
end of message). I would like to know if anyone knows of any problems that
I could encounter from this code and whether or not it is following correct
procedure.

If someone has a link to suitable reference I would be most appreciative if
you could point me toward it. Otherwise, does this code look okay?

SSA

-------

Private pTrdThread As Thread
Private cMREBusy As New ManualResetEven t(False)
Private cMREReady As New ManualResetEven t(True)
Private cMRETerminate As New ManualResetEven t(False)

Private Sub PictureBox1_Mou seMove(ByVal sender As Object, ByVal e As
System.Windows. Forms.MouseEven tArgs) Handles PictureBox1.Mou seMove
Call startThread(e.L ocation)
End Sub

Private Sub startThread(ByV al iParam As Object, Optional ByVal iJustAbort As
Boolean = False)
If (cMREBusy.WaitO ne(0, False)) Then
Call Console.WriteLi ne("Thread has already started...")
Call cMRETerminate.S et()
If (cMREReady.Wait One(3000, False)) Then
Call Console.WriteLi ne("Thread terminated!")
If (Not iJustAbort) Then
GoTo startThreadProc ess
End If
Else
Call Console.WriteLi ne("Could not terminate thread!")
End If
Else
startThreadProc ess:
Call Console.WriteLi ne("Starting thread!")
Call cMREReady.Reset () '//We are not ready to start again
Call cMREBusy.Set() '//We are busy now
Call cMRETerminate.R eset() '//We can be terminated again from now
pTrdThread = New Thread(New ParameterizedTh readStart(Addre ssOf
thread_Callback ))
Call pTrdThread.Star t(iParam)
End If
End Sub

Private Sub thread_Callback (ByVal iParam As Object)
Call Console.WriteLi ne("Thread started with - " & iParam.ToString & " @
" & Environment.Tic kCount)

Dim pGraGraphics As Graphics = PictureBox1.Cre ateGraphics()
Using pGraGraphics

Dim pIntCurItem As Integer
For pIntCurItem = 0 To 60
Call pGraGraphics.Dr awLine(Pens.Bla ck, CType(iParam, Point),
Point.Add(CType (iParam, Point), New Size(1, 1)))
Call Thread.Sleep(10 0)
If (cMRETerminate. WaitOne(0, False)) Then
Call Console.WriteLi ne("Thread terminating @ " &
Environment.Tic kCount)
Exit For
End If
Next

End Using

Call Console.WriteLi ne("Thread exited @ " & Environment.Tic kCount)
Call cMREReady.Set() '//We are now ready to start again
Call cMREBusy.Reset( ) '//We are not busy anymore
End Sub

-------
Mar 2 '06 #1
0 1203

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

Similar topics

12
18902
by: Jerry Sievers | last post by:
Greetings Pythonists; I have limited experience with threaded apps and plenty with old style forked heavyweight multi-processing apps. Using Python 2.3.3 on a Redhat 7.x machine. Wondering if there is a simple way from a main python program to kill a running thread? I see with the 'threading' module the way daemonic threads behave when the main program finishes.
2
309
by: ice88 | last post by:
I would like to execute some code when a thread terminates, in the context of that thread - I guess similar to an ExitThread handler - is it possible in a C# .NET application? I can see a way to execute code when a thread is thrown away - by having per-thread static attributes that are themselves objects, when the thread object associated with that static value is garbage collected, the destructor for the object is driven - but that...
20
3037
by: Doug Thews | last post by:
I ran into an interesting re-pain delay after calling the Abort() method on a thread, but it only happens the very first time I call it. Every time afterward, there is no delay. I've got a delegate inside the UI that I call to update the progress meter. I use the Suspend() and Abort() methods based on button events. I can watch the progress meter increase just fine when the thread is running. When I select Start, I enable the Cancel...
10
1919
by: Fernando Rodríguez | last post by:
Hi, Assume I have Main function that looks like this: static void Main(string args) { Action h1 = new Action(0);
7
2699
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.
3
6178
by: Raj Wall | last post by:
Hi, I have an application that uses a number of sub-threads. What is the best way to do some processing in each thread when the main application is shut down? Is the ThreadAbortException thrown automatically for each thread? Or is there some other event or exception automatically thrown that the thread can "grab" as it is shut down?
1
1750
by: Sanjay | last post by:
Hi All Have an app. On start up it creates a thread and goes to sleep. Either on termination or completion of the worker thread, it triggers the main app to start executing. Question Why is the completion of the worker/child thread triggering the execution of the main app thread. Shouldn't the main app thread remain
5
10604
by: care02 | last post by:
Hi! I have the following problem: I have written a short Python server that creates an indefinite simulation thread that I want to kill when quitting (Ctrl-C) from Python. Googling around has not given me any hints on how to cleanly kill running threads before exiting. Any help is appreciated! Carl
2
3751
by: Mike | last post by:
Hello, Ok I have 2 classes in my project, one is the main form and one is a connection class, at a certain event on my main form a new instance is made of the connection class, and a reference to the main form is passed to its constructor. The connection class opens up a new thread and starts doing work in it, and adds collected data to the main form via a (cross-thread) control invoking delegate.
0
9711
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
10595
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
10343
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...
0
10088
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
9169
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
7633
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
6862
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();...
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.