Windows服务Hit API有时多次

时间:2017-02-28 06:40:13

标签: c# .net windows-services

我使用Windows服务进行呼叫API,在Sql表中获取响应和更新它工作正常但有时候它是Hit API Twice。我无法理智。这是我的代码

 AppCompatDialog dialogVideoView = new AppCompatDialog(context,R.style.dialogFullScreen);
 dialogVideoView.setContentView(R.layout.custom_dialog_video_surface);
 dialogVideoView.show();

这是proccessQue()方法

protected override void OnStart(string[] args)
{
  this.timer = new System.Timers.Timer(15000D);
  this.timer.AutoReset = true;
  this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
  this.timer.Start();
}
protected override void OnStop()
  {
     this.timer.Stop();
     this.timer = null;
 }
protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  this.proccessQue();
}

请帮助我,我哪里出错了。

1 个答案:

答案 0 :(得分:1)

根据我对原始问题的评论,有几点需要注意。

  1. 根据查询结果,API将被命中0次。现在,计时器将为每个间隔异步执行timer_Elapsed()方法。因此,如果processQue()方法花费的时间超过15秒,则可能会为每个项目多次调用API。
  2. 因此,一个选项是Stop定时器执行您的过程逻辑,Start()方法完成后processQue()定时器。如:

    protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
      this.timer.Stop(); //stop the timer 
      this.proccessQue(); //process the queue
      this.timer.Start(); //restart the timer
    }
    

    这样可确保processQue();在再次调用timer_Elapsed()事件之前完成。

    现在,如果processQue()方法出现异常,则执行将不会继续。由你来决定如何处理这个问题,但是一个简单的try .. catch将处理异常(不正确但将会)。

    现在我对代码的第二个顾虑,这与执行多次运行的原因无关,是使用类而不是正确处理事物。

    首先.. Why use a SqlDataAdapter when a SqlDataReader will produce a faster execution.这是基于意见的,但不需要DataTable并且会将整个结果读入内存。你似乎只使用两列(不确定rId来自哪里)的Sql Query,所以不要使用*,而是定义你实际需要的列名。这将减少从Sql Query查询和流式传输的数据量。在小型查询中看起来似乎微不足道,但可以在更大的查询和更大的数据集中发挥重要作用。

    我看到的下一个问题是使用IDisposable而不处理它们。

    1. SqlDataAdapter
    2. StreamReader
    3. SqlCommand
    4. 这些都是继承自IDisposable的类,因此应该包含在using语句中,或者手动调用Dispose()方法。