Reputation: 697
I'm using thread to download something from internet.
I don't have any loop inside my thread method. I'm using StreamReader.ReadToEnd()
method, so
when my thread is downloading something large I want to stop this thread. Preferably without Thread.Abort() method.
Is it possible to give to GC thread to clean, or to finish this?
Upvotes: 3
Views: 627
Reputation: 32418
Don't do a ReadToEnd
, instead create a loop and read X chars at a time (or read a line at a time with ReadLine
). Within the loop check whether an AutoResetEvent
is set (using .WaitOne(0)
), if it is then exit the loop.
Set the reset event (using Set
) in your other thread when you want to stop the download.
Upvotes: 12
Reputation: 17498
You could use the BaseStream BeginRead() async method. You're better off using this rather than spawning your own dedicated thread (which consumes 1MB of committed memory). The async methods are more efficient as they use I/O completion ports.
new StreamReader(aStream).BaseStream.BeginRead()
Here's some more info http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx
A related thread on stopping an async read.
Upvotes: 2
Reputation: 40032
What George Duckett says but you could use .Net 4 Task
class to start the thread/asynchronous task and pass in a CancellationToken
and in the loop check if IsCancellationRequested
= true
Upvotes: 0