Problems with thread cancellation.
C#
3
Posts
2
Posters
0
Views
1
Watching
-
I used the "Abort()" method of class Thread in a program to cancel a thread. It seemed to function correctly, but after the main program exited, the process can still be found in processes tab of "Windows Task Manager". Whenever this line is not executed, the problem does not occur. Is it inappropriate to cancel a thread in this manner?
-
I used the "Abort()" method of class Thread in a program to cancel a thread. It seemed to function correctly, but after the main program exited, the process can still be found in processes tab of "Windows Task Manager". Whenever this line is not executed, the problem does not occur. Is it inappropriate to cancel a thread in this manner?
- Do you catch the ThreadAbortException in a loop like that?
try{ for(...){ try{ }catch{ ... } } }catch(ThreadAbortException){ ... }
Then the thread can run for hours without doing anything. 2) You can stop the thread a clean way. Declare a boolean variable, and check it's value in the thread method:bool threadStopped = false; ... private void myThreadMethod(){ doSomething(); if(stopped){ return; } doSomethingElse(); if(stopped){ return; } doAnything(); if(stopped){ return; } ... }
With that stop-variable you don't need Thread.Abort() and the try/catch stuff, because the thread stops when you setthreadStopped = true
.
- Do you catch the ThreadAbortException in a loop like that?
-
- Do you catch the ThreadAbortException in a loop like that?
try{ for(...){ try{ }catch{ ... } } }catch(ThreadAbortException){ ... }
Then the thread can run for hours without doing anything. 2) You can stop the thread a clean way. Declare a boolean variable, and check it's value in the thread method:bool threadStopped = false; ... private void myThreadMethod(){ doSomething(); if(stopped){ return; } doSomethingElse(); if(stopped){ return; } doAnything(); if(stopped){ return; } ... }
With that stop-variable you don't need Thread.Abort() and the try/catch stuff, because the thread stops when you setthreadStopped = true
.
- Do you catch the ThreadAbortException in a loop like that?