views:

80

answers:

3

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.

A: 

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;
    }
sadboy
A: 

You will have to run the task in another thread, and monitor from your main thread whether it's running longer than 15 seconds:

string result;
Action asyncAction = () =>
{
    //do stuff
    Thread.Sleep(10000); // some long running operation
    result = "I'm finished"; // put the result there
};

// have some var that holds the value
bool done = false;
// invoke the action on another thread, and when done: set done to true
asyncAction.BeginInvoke((res)=>done=true, null);

int msProceeded = 0;
while(!done)
{
    Thread.Sleep(100); // do nothing
    msProceeded += 100;

    if (msProceeded > 5000) break; // when we proceed 5 secs break out of this loop
}

// done holds the status, and result holds the result
if(!done)
{
    //aborted
}
else
{
    //finished
    Console.WriteLine(result); // prints I'm finished, if it's executed fast enough
}
Jan Jongboom
+2  A: 

Since you say "web request", I assume that the stream reader wraps a System.IO.Stream which you obtained from a HttpWebRequest instance by calling httpWebRequest.GetResponse().GetResponseStream().

If that's the case, you should take a look at HttpWebRequest.ReadWriteTimeout.

Wim Coenen