Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point is the Thread.CurrentThread evaluated?

In the following code:

ThreadStart ts = new ThreadStart((MethodInvoker)delegate
        {
            executingThreads.Add(Thread.CurrentThread);
            // work done here.
            executingThreads.Remove(Thread.CurrentThread);
        });
        Thread t = new Thread(ts);
        t.Start();

Perhaps you can see that I'd like to keep track of the threads that I start, so I can abort them when necessary.

But I worry that the Thread.CurrentThread is evaluated from the thread that creates the Thread t, and thus aborting it would not abort the spawned thread.

like image 764
user420667 Avatar asked Jul 19 '26 09:07

user420667


2 Answers

Aborting threads is never a good idea. If you are 100% positive that whatever task you are performing in the thread you want to abort will not corrupt any state information anywhere else then you can probably get away with it, but its best to avoid doing so even in those cases. There are better solutions like flagging the thread to stop, giving it a chance to clean up whatever mess it may leave behind.

Anyhow, answering your question, Thread.CurrentThread is executing in the method invoked when the new thread starts executing, therefore it will return the new thread, not the thread where the new thread was created (if that makes sense).

like image 103
InBetween Avatar answered Jul 20 '26 23:07

InBetween


In the code you have given, Thread.CurrentThread is called in the context of the thread t and not its creator.

Also, aborting threads is morally equivalent to killing puppies.

like image 34
David Heffernan Avatar answered Jul 20 '26 22:07

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!