views:

165

answers:

2

Hi, I've just started with C#. I'm running an object's function as a thread (new Thread(myFunc).Start()).

Does the thread kill itself when the function is finished or must I manually get rid of it? If I must, what is the best way to do it (I may not know when it finishes etc)?

Thanx!

+7  A: 

Yes the thread will exit when the function returns. If it is a long-running task and you want to be sure it has finished before the program exits, you can use Thread.Join which will block the main thread until the other thread completes.

Lee
+2  A: 

Threads last for the duration of their function; after the function finishes, the thread will automatically dies.

However, if you want to execute a relatively quick function in the background, it's better to use the ThreadPool than to start up a new thread for it. By using the ThreadPool, you will be reusing a set of threads that are automatically maintained by the .Net framework, and you'll avoid the overhead of creating a new thread.

For example:

ThreadPool.QueueUserWorkItem(delegate { myFunc(); });
SLaks