简体   繁体   中英

C# Update Application Based on Updates in DB

I'm creating a chatting application in C# where clients can chat privately, however I'm struggling to update the messages based on changes within the DB (sql-server).

Should I create a constant running thread which requests data after the last message id outputted? I think this may be inefficient, is there other methods? Or could you recommend a better method?

   public void Display_Messages(dynamic listbox, int conversation_id)
{
    Connection _connection = new Connection();
    _connection.conn.Open();
    string sql = "SELECT userId, text, messageId FROM message WHERE conversationId =" + conversation_id + ";";  // Update Later to use PS
    dynamic command = new SqlCommand(sql, _connection.conn);
    dynamic data_reader = command.ExecuteReader();
    while (data_reader.Read())
    {
        listbox.Items.Add(data_reader.GetValue(0) +":"+data_reader.GetValue(1));
    }
    data_reader.Close(); command.Dispose(); _connection.conn.Close();
}

You can use SQL Server's broker service which notifies your custom data changes, but there must not be too many listeners on it for performance considerations. The polling mechanisms usually are not efficient enough and put a constant load on the system even when there is no new data to be notified.
You can find all the information you need to use the broker service online.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM