Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a thread in C#?

I wanted to try my luck in threading with C#, I know a few things about threading in C.

So I just wanted to ask if i wanted to terminate a thread, I should do it with smt.Abort() or it will "kill itself" after the function ends?

Also, is there something like pthread_exit() in C in C#?

like image 415
Bill Skiadas Avatar asked Jan 03 '13 00:01

Bill Skiadas


People also ask

How do you terminate a thread in C?

You can stop the thread using pthread_cancel : pthread_cancel(thread1);

How do you terminate a thread?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

How do you cancel a thread on Pthread?

The pthread_exit() function terminates the calling thread, making its exit status available to any waiting threads. Normally, a thread terminates by returning from the start routine that was specified in the pthread_create() call which started it.


1 Answers

Thread.Abort will "kill" the thread, but this is roughly equivalent to:

Scenario: You want to turn off your computer

Solution: You strap dynamite to your computer, light it, and run.

It's FAR better to trigger an "exit condition", either via CancellationTokenSource.Cancel, setting some (safely accessed) "is running" bool, etc., and calling Thread.Join. This is more like:

Scenario: You want to turn off your computer

Solution: You click start, shut down, and wait until the computer powers down.

like image 80
JerKimball Avatar answered Oct 05 '22 02:10

JerKimball