I have two application(A & B) and a SQL table (Microsoft SQL Server 2014) with columns as below:
|| Guid || Random || WriteTime || Flag || ReadTime ||
Application A will insert the new row with new Guid, random, WriteTime and Flag.
(Code A)
private void WriteIntoDB(int random)
{
SqlCommand cmd = new SqlCommand();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand command = conn.CreateCommand();
command.Connection = conn;
command.Transaction = trans;
command.CommandText = string.Format("INSERT INTO " + "MyTable" + "([Guid],[Random],[WriteTime],[Flag])" + "VALUES(@Guid,@Random,@WriteTime,@Flag)");
command.Parameters.AddWithValue("@Guid", Guid.NewGuid());
command.Parameters.AddWithValue("@Random", random);
command.Parameters.AddWithValue("@WriteTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
command.Parameters.AddWithValue("@Flag", 0);
command.ExecuteNonQuery();
trans.Commit();
}
}
This function will be called six times in TimerA_Tick(with TimerA interval = 1500 millisecond)
And Application B also has a TimerB with interval = 1000 millisecond. In TimerB_Tick, it will select all rows where Flag=0, and change it to 1, also fill in column 'ReadTime'.
(CODE B)
private DataSet DS = new DataSet();
private void ChangeFlag(SqlConnection conn)
{
string cmd = "SELECT * FROM MyTable WHERE Flag = 0";
SqlDataAdapter da = new SqlDataAdapter(cmd, conn);
DS.Tables["test"].Clear();
da.Fill(DS.Tables["test"]);
lock (DS.Tables["test"])
{
using (new SqlCommandBuilder(da))
{
DataRow[] rows = DS.Tables["test"].Select("Flag=0 ", "WriteTime ASC");
foreach (DataRow row in rows)
{
if (Convert.ToInt32(row["Random"]) <= 50)
{
//do something.
}
row["ReadTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
row["Flag"] = 1;
da.Update(DS.Tables["test"]);
}
}
}
}
I expect 'Random' which was written in the database first also to be processed by ApplicationB first. Most of the data was, but some of them were not... The link below is part of that SQL Table, ordered with "WriteTime' ascendant.
There's a row that seems to be processed previously to the data which is written earlier. But I don't know why it happened(and more than one time), also got no idea how to fix it.