简体   繁体   English

如何修复 C# 中的 Timer tick 错误?

[英]How to fix this Timer tick error in C#?

I am using this code to receive data from an Internet address.我正在使用此代码从 Internet 地址接收数据。 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.定时器间隔为 30 秒。

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.错误:未处理 WebException。 The remote server returned an error: (500) Internal Server Error.远程服务器返回错误:(500) 内部服务器错误。

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).第一步是您应该编写 try/catch 块来处理错误(或只是忽略)。 Also see what type of exceptions you are getting.另请查看您遇到的异常类型。

Alternatively you can use sockets to do the function recursively with some wait time.或者,您可以使用 sockets 递归地执行 function 并等待一些时间。

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.如果它是(500) Internal Server Error ,那么您必须检查服务器以查看错误是什么。 Since it's localhost I assume you have access to the server.由于它是本地主机,我假设您可以访问服务器。 That's where there error's going to be.那就是会出现错误的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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