Sorry for creating another topic because my question wasn’t specific and not accurate to resulting the thread to be closed and deleting.
I have a chat application, i want my application not to hang while the textblock for chat dialogue is refreshing every a second to retrieve the current conversation. How can i prevent my application not to stop and resume every second?
I actually used the google but in return i found no specific answer.
Here is my code:
public MainWindow()
{
InitializeComponent();
timerChatRefresh = new DispatcherTimer();
timerChatRefresh.Interval = new TimeSpan(0, 0, 1);
timerChatRefresh.IsEnabled = false;
timerChatRefresh.Tick += new EventHandler(timerChatRefresh_Tick);
timerChatRefresh.Start();
}
void timerChatRefresh_Tick(object sender, EventArgs e)
{
ChatRefresh();
}
private void ChatRefresh()
{
conn = new MySqlConnection("Server=...; Database=...; Uid=...; Password=...;");
ds.Clear();
textBlockChatArea.Text = "";
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = "select * from chatmessagetbl";
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(ds, "chatmessagetbl");
foreach (DataRow item in ds.Tables["chatmessagetbl"].Rows)
{
textBlockChatArea.Text += item["username"].ToString() + ": " + item["message"].ToString() + "\n";
}
conn.Dispose();
}
You will need to update the textbox on a thread that isn’t the UI thread.
The code I’ve provided isn’t very clean, it’s not meant to be a final solution that you can copy and paste (though it’ll probably work), it’s just to try to help you in the right direction and show you one way that it can be done with threading.
EDIT
To try and clear up a point I made in comments about using a list control instead of a textbox, I’ve added the following pseudo program to try and explain what I meant.
To bind the listbox to the new Entries property you do something like this in the XAML.