views:

93

answers:

6

I have multiple downloads running in threads. I want to close the stream, say when user hits pause/stop download. How could I close the filestream of a download running in a thread?

+6  A: 
stream.Close();
John Saunders
Can you give a more concise answer?
Yuriy Faktorovich
I don't think it can get more concise. Just close the stream. What's preventing you?
John Saunders
+4  A: 

You could use a flag in shared memory and check it periodically from the thread to determine whether to start waiting (or close the stream) or to download the next chunk.

Eric Mickelsen
+1  A: 

Well one way you can do it is stream the buffer within a thread, within a loop. Each time you are about to grab another chunk of data, check to see if your pause property has been enabled. If it has, simply skip the iteration until it has been set back to true.

This way, your stream doesn't get closed, but it pauses downloading any additional data.

George
A: 

You can have an event object (MaunalResetEvent\AutoResetEvent). Signal the event when you need to stop the thread. In your thread routine check if event is signalled and stop processing along with closing your file stream.

serge_gubenko
Thread.Abort is a nuclear option and should be avoided in normal processing (such as a user "pause" or "cancel" operation). See http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation for discussion of problems and alternatives.
itowlson
A: 

Rather than calling thread.Abort() you could use a Background worker thread and use the built in cancel event.

You call worker.CancelAsync() to raise the event. This could be from a button or key press for example.

Then in the worker_DoWork method you have the following:

if (worker.CancellationPending)
{
    // close the stream
}
else
{
    // Carry on downloading
}

inside your loop that's performing the download

ChrisF
A: 

Would this work? Just a suggestion, i'm not super hot with threads. Keep a hold of the class handling the download, would this work?

    public class Threader
        {
            MyDownloader md;

            public void UserClicksDownload()
            {
                md = new MyDownloader();
                Thread t = new Thread(md.DownloadStuff);            
                t.Start();

                Thread.Sleep(100);
            }

            public void UserClicksStop()
            {
                t.Abort();
                t = null;
                md.StopDownloading();
            }
        }

        public class MyDownloader 
        {
            public void DownloadStuff()
            {
                while (true)
                {
                    Console.WriteLine("downloading stuff!");
                }
            }

            public void StopDownloading()
            {
                Console.WriteLine("Tidy up you downloads here");
            }
        }
runrunraygun