0

我将我的程序作为 Windows 服务运行,并且每次经过时间(我已设置为 1 分钟)都尝试发送 HTTP 请求。我在服务器端尝试做的只是写一个从查询字符串中获取的值。写入文件有效,但我注意到发送了一些重复的值?

   protected override void OnStart(string[] args)
    {
        try
        {
            eventLog1.WriteEntry("In OnStart, this is another new build 016");

            timer1 = new System.Timers.Timer(5000D);
            timer1.AutoReset = true;
            timer1.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer1.Start();

            eventLog1.WriteEntry("This is after calling start method");
        }
        catch (Exception exxx)
        {
            eventLog1.WriteEntry(exxx.Data.ToString());
        }
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In onStop."); 
    }

    private static void timer_Elapsed(object source, ElapsedEventArgs e)
    {
        timer1.Stop();
        el.WriteEntry("The Elapsed event was raised at " + i);
        i++;// i  is initialized to 0

        request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.example.com/Test.php?test=" + i);
        request.Method = "GET";
        request.Timeout = 5000;


        try
        {
            request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
        }
        catch (System.Net.WebException e1)
        {
            el.WriteEntry("Exception 1:" + e1.Message);
        }
        catch (System.Net.ProtocolViolationException e2)
        {
            el.WriteEntry("Exception 2:" + e2.Message);
        }
        catch (System.InvalidOperationException e3)
        {
            el.WriteEntry("Exception 3:" + e3.Message);
        }
        timer1.Start();
    }

    private static void FinishWebRequest(IAsyncResult result)
    {
        request.GetResponse().Close();
    }

我在文件中注意到的内容类似于 1,2,1,1,3,2,2,1,1。我看不出我的代码有什么问题。HttpWebRequest 是否有可能发送重复请求?

4

1 回答 1

0

我认为代码是正确的。我认为您也在其他地方使用 i 变量。尝试将 i 更改为不常见的其他内容

HttpWebRequest 从不发送相同的请求重复请求。

例如,让我们假设 HttpRequest 是重复的,那么输出应该是 1,1,1,1,2,2,2,3 ......

于 2013-06-13T14:23:24.157 回答