rian
rian

Reputation: 21

Closing a stream in a thread that is already running [C#]

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?

Upvotes: 2

Views: 489

Answers (6)

gingerbreadboy
gingerbreadboy

Reputation: 7769

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");
            }
        }

Upvotes: 0

serge_gubenko
serge_gubenko

Reputation: 20482

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.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137118

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

Upvotes: 0

George Johnston
George Johnston

Reputation: 32258

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.

Upvotes: 1

Eric Mickelsen
Eric Mickelsen

Reputation: 10377

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.

Upvotes: 4

John Saunders
John Saunders

Reputation: 161773

stream.Close();

Upvotes: 6

Related Questions