开发者

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

开发者 https://www.devze.com 2022-12-17 16:24 出处:网络
I have multiple downloads running in threads. I want to close the stream, say when user hits pause/stop d开发者_开发知识库ownload. How could I close the filestream of a download running in a thread?st

I have multiple downloads running in threads. I want to close the stream, say when user hits pause/stop d开发者_开发知识库ownload. How could I close the filestream of a download running in a thread?


stream.Close();


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.


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.


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号