简体   繁体   中英

How to fix this Timer tick error in C#?

I am using this code to receive data from an Internet address. However, when the timer ticks at first time the connection is OK and program works properly. But in second time, an error is raised from this line :

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I want to know how to fix this problem.

Timer interval is 30 seconds.

Code:

private void timer1_Tick(object sender, EventArgs e)
{
    WebRequest request = WebRequest.Create("http://localhost  
    /go/online.asp?prog=y&rln=" + Properties.Settings.Default.cos);

    request.Credentials = CredentialCache.DefaultCredentials;

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);

    string responseFromServer = reader.ReadToEnd();

    reader.Close();
    dataStream.Close();
    response.Close();
}

Error: WebException was unhandled. The remote server returned an error: (500) Internal Server Error.

Normally when I use a timer, I stop the timer before starting to process and then restart it when done processing. Try that and see if it works.

Mostly it happens because of the previous request is not completed while next timer ticks. The first step is you should write try/catch block to handle the errors (or just to ignore). Also see what type of exceptions you are getting.

Alternatively you can use sockets to do the function recursively with some wait time.

maybe you can deactivate the timer in the timer event handler, and at the end reactive it.

If it's an (500) Internal Server Error then you'll have to check with the server to see what the error is. Since it's localhost I assume you have access to the server. That's where there error's going to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM