【问题标题】:HttpWebRequest making duplicate request?HttpWebRequest 发出重复请求?
【发布时间】:2013-06-13 22:23:24
【问题描述】:

我正在将我的程序作为 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 是否有可能发送重复请求?

【问题讨论】:

  • 偶然在停止并重新启动服务后会这样做吗?每次启动服务时,您都在订阅一个新的计时器事件,但如果您之前订阅了另一个计时器,您永远不会取消订阅.您的 OnStop 实际上应该是定时器的 Dispose,因为它实现了 IDisposable。如果停止/启动是您的问题,这将解决问题。
  • 不,我只是让它运行而不启动或停止服务。而且我确定服务没有介于两者之间,因为我确实记录了停止事件。

标签: c# windows-services httpwebrequest


【解决方案1】:

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

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

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

【讨论】:

  • 我尝试更改为唯一变量,仍然是同样的问题。另外,我已经记录了我发出的 http 请求,我确信它是独一无二的。是什么赋予了?这意味着就像你说的,HttpWebRequest 永远不会发送重复的请求。也许网络服务器本身正在重新发出重复的 http 请求?
猜你喜欢
  • 1970-01-01
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多