我使用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();
}
请帮助我,我哪里出错了。
答案 0 :(得分:1)
根据我对原始问题的评论,有几点需要注意。
timer_Elapsed()
方法。因此,如果processQue()
方法花费的时间超过15秒,则可能会为每个项目多次调用API。因此,一个选项是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
而不处理它们。
SqlDataAdapter
StreamReader
SqlCommand
这些都是继承自IDisposable
的类,因此应该包含在using
语句中,或者手动调用Dispose()
方法。