Main Site Documentation

What is the difference between these Threads?


#1

I there a difference in starting a thread in these 2 ways.

new Thread(test).Start();

or

private Thread thread = null;

thread = new Thread(new ThreadStart(test));
thread.Start();


#2

No. Except in the first example you do not have a reference to the thread.


#3

Also the second one gives you the ability to do things like set the priority before calling start. Otherwise the are the same.


#4

Thinking about this, if you do not have a reference to a thread and gc runs then will the thread be disposed? I never tried this!


#5

I have been using new Thread(test).Start(); since i started learning and those threads have been running solid. overnight anyway.

Seems as though i should be getting used to the other way.


#6

When a thread is started its use count is incremented by one, and when the thread exits it is decremented. So, a running thread without a reference is not GC’d. Works same way on full .NET.


#7

Good to know because IIRC I had trouble with timers, threads are different. Thanks Mike


#8

Both the desktop framework and the NETMF use what’s known as a “mark-and-sweep” garbage collector. That means that there are no reference counts stored or used. When the GC goes to do it’s thing, it starts by marking every object as “unreachable”, and then starting at all the “roots”, it goes through and anything it can find by traversing references it marks as “reachable”. When it’s done with the “sweep”, it collects anything that is still marked as unreachable.

This way, there’s no problems with circular references.

Fortunately, threads are “roots”, so they aren’t ever collected.

This is the subject of a famous AI koan: http://catb.org/jargon/html/koans.html#id3141202


#9

It might be more robust to do things the long winded way…

You could then implement:
a) != null check before calling Thread.start()
b) consider adding a try/catch around the start() (especially if your running multiple threads and resources get low).


#10

well actually the example was simplified to make a point. Basically what i wanted to know is when a method crates multiple instances of a class, and in that class it has the using statement and a while loop in there. i just wanted to make sure that before a new instance was made the previous one was released. .