473,805 Members | 2,077 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threads so darn hard to understand

Hello, recently I've been trying to figure out how the heck to just
destroy a thread.

I have since rewritten the code in question, but what I was trying to do
was to use the .Abort() method, but that would fail if the thread was in
a Suspended case.

Now, my book doesn't even hint (Deitel Developer Series, C# for
Experienced Programmers) that a thread might exist in more than one
state, which was also part of my problem. (Fortunately during a period
of high inspiration I managed to figure out that ThreadState is a
bitfield and OR'ing the threadstates work).

However, it appears to be impossible to do the following:
For a given thread, stop it.

I have tried exhaustively checking the state of the thread and doing the
appropriate .Resume(), .Interrupt(), etc, however by the time I do
..Abort(), I cannot guarantee that the statement will execute successfully.

Currently I've implemented my very own .AbortRedrawing () method, but
I've wasted hours trying to understand threads themselves. I do not
understand why there's no .ForceAbort() method.

If anyone could show me some documentation (more useful than the "wow,
here's how to create three threads!" kind of tutorial), that'd be great.

(Sorry if the tone is a bit... But I've been wrestling with it for a
while).

Thanksyou.

(PS: I have since discovered the Timer() class, which would've fit my
purpose better, but the fact stands that I still need to learn more
about threading in .NET)
Nov 17 '05 #1
9 1445
Arafangion <Ar********@inv alid.email.addr ess.com> wrote:
Hello, recently I've been trying to figure out how the heck to just
destroy a thread.
Using Abort (or even Interrupt) is usually a bad way of doing it.
Currently I've implemented my very own .AbortRedrawing () method, but
I've wasted hours trying to understand threads themselves. I do not
understand why there's no .ForceAbort() method.
Because aborting threads almost always inherently leads to instability.
If anyone could show me some documentation (more useful than the "wow,
here's how to create three threads!" kind of tutorial), that'd be great.


See http://www.pobox.com/~skeet/csharp/threads/

I hope it fits your needs.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2
Jon Skeet [C# MVP] wrote:
Because aborting threads almost always inherently leads to instability.

See http://www.pobox.com/~skeet/csharp/threads/

I hope it fits your needs.

Thanks for that website, it does clear alot up.
Nov 17 '05 #3
> Hello, recently I've been trying to figure out how the heck to just
destroy a thread.

Threading is not that easy to do, unless you have a lot of programming
experience.
The problem with threads is not that the code is difficult, but when threads
interact with each other you could get problems that is very hard to
visualize.

Some things I have learend about threads.
* Mark your functions/propertes when they are thread safe in startup mode
and in run mode.
I use this notation {RWrw} RW means it is safe to Write/Read even during
setting up the thread.
The rw is that it is safe to read/write during running.

If I write this {--rw} then I should pause the thread if I initialize/call
these this property/function.
Basically creating a thread in syspended mode, the fill in these variables
and then start the thread.

If I write this {----} Then this propertie function is totally none-thread
safe and must not be called while the thread is running from outside the
thread. Normally these functions/property will be marked private since it is
perfectly safe inside the thread to use it's own variables functions. The
problem only occurs when the functions/properties arre called from another
thread.

If you create threads try to avoid as much communication between 2 threads
and if you do it, then do it in a atomic operation. Try to create a
structure that contains all the parameters you want to access, then lock the
thread, copy the internal properties to that structure and the unlock. This
way you have all parameters synchronized with each other and reduces the
time waiting for e loack release.

Stopping a thread is another problem. You should send a command to request a
thread to stop and then you wait. Aborting a thread is not a good way to do.
So your code must be good. But if you have to stop multiple threads, then
the best way to do is to loop through all threads to stop itself, and then
wait untill all of them signaled that they are stopped. This is the fastest
way to stopp multiple threads. But you might get an out of order
synchronization problem. Suppose that you have 10 threads, you loop from
1..10 to send the stop command, then the stop process could be out of
sequence e.g. 5 stops, then 2 then 9 then 3 then 4 then 1 then 7...

Don't feel bad if you have a hard time to learn it. It took me also a hell
of a time to get it right.

Ah one more thing, keep those critical sections as low as possible, because
if you try to access a locked property then you code stalls because it must
wait untill it gets released. If this stalled thread happens to also lock a
critical section then it migth stall another thread on its turn. You will
see that the stall gives a big performance penalty that is not lineair if
you gave more threads. It is more quadratic in nature. I mean, If you use 10
threads, then you migth lose 100 ms, but if you use 20 threads you might
stall for 400 ms... So only lock when it is abselutely necessary and try to
lock only the things that cannot go wrong and is very fast.

For example, if you load a file in a thread, use a second buffer, load the
file (unlocked) in the temporary buffer and then copy that buffer to your
second thread locked. This way if you have a network hickup, then code does
not freeze. Like access denied.

Sadly enough there is no one fit all solution when you work with threads. It
must be custom made.

Good luck. :-)

--
Nov 17 '05 #4
Olaf Baeyens wrote:
Sadly enough there is no one fit all solution when you work with threads. It
must be custom made.


Ok, I think I understand what one has to do now, although the actual
code itself will take practise, but I do wonder why there isn't at least
a generic .Interrupt() method that is _guaranteed_ to raise the relevant
exception in the thread.
Nov 17 '05 #5


Arafangion wrote:
but I do wonder why there isn't at least
a generic .Interrupt() method that is _guaranteed_ to raise the relevant
exception in the thread.


For one thing, the thread can be blocked outside the control of the CLR,
for example in some machine-code.

Even worse, it can be blocked inside the OS in a non-interruptable wait.

Valid async-interruptable machine- (and c-,...) -code is *insanely* hard
to write.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #6
> > Sadly enough there is no one fit all solution when you work with
threads. It
must be custom made.


Ok, I think I understand what one has to do now, although the actual
code itself will take practise, but I do wonder why there isn't at least
a generic .Interrupt() method that is _guaranteed_ to raise the relevant
exception in the thread.

I don't know what you mean with generic Interrupt()

But I do know that VB and COM? have a multithread model called appartment
threading that automatically locks the properties and methods when called
(if I understand this correctly). So for beginners this might help a little
but it is not the most efficient way of doing things.

--

Nov 17 '05 #7
VB has apartment threading? I wasn't aware of that.

--
Regards,
Alvin Bruney - ASP.NET MVP

[Shameless Author Plug]
The Microsoft Office Web Components Black Book with .NET
Now available @ www.lulu.com/owc, Amazon.com etc
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:42******** *************@n ews.skynet.be.. .
> Sadly enough there is no one fit all solution when you work with threads. It > must be custom made.


Ok, I think I understand what one has to do now, although the actual
code itself will take practise, but I do wonder why there isn't at least
a generic .Interrupt() method that is _guaranteed_ to raise the relevant
exception in the thread.

I don't know what you mean with generic Interrupt()

But I do know that VB and COM? have a multithread model called appartment
threading that automatically locks the properties and methods when called
(if I understand this correctly). So for beginners this might help a
little
but it is not the most efficient way of doing things.

--

Nov 17 '05 #8
> VB has apartment threading? I wasn't aware of that.

I am not a VB programmer, I only see it for minimum 1 meter distance. :-)
Afraid to come near. :-)

But if I Google, then I see many references to VB and apartment threading
(STA/MTA) I believe it has been available since VB 5 with SPxx and VB 6.
Nov 17 '05 #9
i'll have to do some looking around. bahhhh never mind. i'm not that
interested in it anyway

--
Regards,
Alvin Bruney - ASP.NET MVP

[Shameless Author Plug]
The Microsoft Office Web Components Black Book with .NET
Now available @ www.lulu.com/owc, Amazon.com etc
"Olaf Baeyens" <ol**********@s kyscan.be> wrote in message
news:42******** *************** @news.skynet.be ...
VB has apartment threading? I wasn't aware of that.

I am not a VB programmer, I only see it for minimum 1 meter distance. :-)
Afraid to come near. :-)

But if I Google, then I see many references to VB and apartment threading
(STA/MTA) I believe it has been available since VB 5 with SPxx and VB 6.

Nov 17 '05 #10

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

Similar topics

1
2135
by: Huzefa | last post by:
I am working on a amll project in Java that includes many classes. Each of the classes has a Logger object. I have associated a FileHandler with each of these Logger objects. The file is the same for each of these classes "log.xml" Now I want all the classes to log to the same file. However, this does not happen. Each class creates its own log file. The base class uses the file "log.xml". Each subsequent class creates a log file...
8
2317
by: andrewpalumbo | last post by:
I'm trying to write some code which will split up a vector into two halves and run a method on the objects in the vector using two seperate threads. I was hoping to see a near linear speedup on an SMP machine, but I'm finding that the code below takes almost exactly the same amount of time as when I iterate through the vector, and don't use any threads at all (using only one processor). I'm running this on a Dual Athlon machine under...
23
2503
by: Antoon Pardon | last post by:
I have had a look at the signal module and the example and came to the conclusion that the example wont work if you try to do this in a thread. So is there a chance similar code will work in a thread? -- Antoon Pardon
11
1913
by: Qiangning Hong | last post by:
A class Collector, it spawns several threads to read from serial port. Collector.get_data() will get all the data they have read since last call. Who can tell me whether my implementation correct? class Collector(object): def __init__(self): self.data = spawn_work_bees(callback=self.on_received) def on_received(self, a_piece_of_data):
6
1489
by: Don S | last post by:
I'm wondering if there is any scripts out there for webifying usernet threads such as google does when you read their groups. I've noticed in a number of usenet groups that I frequent a ton of good threads that aren't quite right for a FAQ but would be darn good to have stored somewhere. Call them GTs for Good Threads. Basically what I'm looking for is scripts (perl?) that could be used to create a top page something like:
22
4076
by: Jeff Louie | last post by:
Well I wonder if my old brain can handle threading. Dose this code look reasonable. Regards, Jeff using System; using System.Diagnostics; using System.IO; using System.Threading;
35
4050
by: Carl J. Van Arsdall | last post by:
Alright, based a on discussion on this mailing list, I've started to wonder, why use threads vs processes. So, If I have a system that has a large area of shared memory, which would be better? I've been leaning towards threads, I'm going to say why. Processes seem fairly expensive from my research so far. Each fork copies the entire contents of memory into the new process. There's also a more expensive context switch between...
2
4572
by: jgbid | last post by:
Hi, I'm trying to build an IP Scanner inc c# for a specific port (80) and for specific IP Ranges. For example 24.36.148.1 to 24.36.148.255 My first step was to use TcpClient, but there are nothing to control Timeout Connection... and I wasn't interested to wait 25-30sec for each ip. After some search, it's look like Socket was the solution with
16
15575
by: WATYF | last post by:
Hi there... I have a huge text file that needs to be processed. At the moment, I'm loading it into memory in small chunks (x amount of lines) and processing it that way. I'd like the process to be faster, so I'd like to try creating multiple threads, and having them load different chunks of the file at the same time and process it asynchronously. Is it possible to do something like that, and if so, what would be needed to do so?
0
9716
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
9596
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10609
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
10360
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
10366
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
9185
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
7646
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...
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
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.