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
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.
source to share
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 http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx
Associated thread when stopping reading async.
source to share