How to kill a Thread in C # instantly

I am using a stream to download something from the internet. I don't have a loop inside a thread method. I am using a method StreamReader.ReadToEnd()

, so when my thread downloads something big, I want to stop that thread. Preferably without Thread.Abort () method. Is it possible to let the GC clear the thread, or to end it?


source to share

3 answers

Don't ReadToEnd

, instead create a loop and read x-characters at a time (or read a line at a time with ReadLine

). In the loop, check if set AutoResetEvent

(using .WaitOne(0)

) if it exits the loop.

Set a reset event (using Set

) on another thread when you want to stop the download.



You can use async method for BeginRead () BaseStream. You are better off using this rather than creating your own dedicated thread (which consumes 1MB of memory). Asynchronous methods are more efficient because they use I / O completion ports.

new StreamReader(aStream).BaseStream.BeginRead()


Here is some more info

Associated thread when stopping reading async.

Stop thread .BeginRead ()



Which is what George Duckett says, but you can use the .Net 4 class Task

to start the thread / async task and pass in CancellationToken

and in the loop to check if IsCancellationRequested

= true



All Articles