Search code examples
c#httprequeststreamreader

c# stop a streamreader after a few seconds. Is this possible?


I have web request and i read information with streamreader. I want to stop after this streamreader after 15 seconds later. Because sometimes reading process takes more time but sometimes it goes well. If reading process takes time more then 15 seconds how can i stop it? I am open all ideas.


Solution

  • Use a System.Threading.Timer and set an on tick event for 15 seconds. It's not the cleanest but it would work. or maybe a stopwatch

    --stopwatch option

            Stopwatch sw = new Stopwatch();
            sw.Start();
            while (raeder.Read() && sw.ElapsedMilliseconds < 15000)
            {
    
            }
    

    --Timer option

            Timer t = new Timer();
            t.Interval = 15000;
            t.Elapsed += new ElapsedEventHandler(t_Elapsed);
            t.Start();
            read = true;
            while (raeder.Read() && read)
            {
    
            }
        }
    
        private bool read;
        void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            read = false;
        }