I am working on a c# service(built as a console app for now for debugging) that will is polling against a DB tables row count. Upon a new row being added to the table(INSERT) the application will kick off to begin some other processing however i'm having issue with the polling logic.
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
//1 second pause
SqlConnection conn = new SqlConnection(@"OMITTED"); //connection to DB
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("OMITTED", conn); //Query to fil poll table comparator
DataTable table = new DataTable(); //establishing new instance to fill
adapter.Fill(table);
int prevRowCount = table.Rows.Count; // establishing comparator value
while (true) //loop
{
adapter.Fill(table);
if (table.Rows.Count > prevRowCount)
{
Console.WriteLine("New records");
prevRowCount = table.Rows.Count;
}
Thread.Sleep(1000); //1 second pause
}
}
}
}
Watching the data table variable in debug and prevrowcount, they both seem so be sitting at 2, however the if is still stepped into. And then upon the next adapter.Fill it seems the value is getting incremented by the row count every iteration. So my question(s):
When using this structure do I need to clear the instance of the variable every loop after the if, if so how?
Why is the if performing upon the first if iteration when the data table variable only has 2 rows and the prevrowcount variable is 2?
I've tried moving the adapter fill, removing it from the while. Different ways of setting, I am not understanding why the if is being performed.
1条答案
按热度按时间pgky5nke1#
I would suggest you use SQL table dependency. you will not need to write code to poll and do all this.
you can refer to this , I have personally used this in my project.
you will get a notification of inserted/modified/deleted records. you can use it accordingly.
Even Microsoft has provided this , but I have never used it.