RustamIS
RustamIS

Reputation: 697

How to kill Thread in C# instantly

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

Answers (3)

George Duckett
George Duckett

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

Razor
Razor

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.

Stop Stream.BeginRead()

Upvotes: 2

Jon
Jon

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

Related Questions