I'm developing an application that needs to check the DB every 5 sec (with a query) and when it happens, the GUI freezes for about 0.5sec and that its really annoying.
This is my code, I'm using "System.Windows.Forms.Timer" but i can change it.
private void TimerBackground(Object myObject, EventArgs eventArgs)
{
// code to check from DataBase that takes about 0.5 sec and freezes the GUI
// Then it will display the result to a label in a form
}
void main(){
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Tick += new EventHandler(TimerBackground);
myTimer.Interval = 5000;
myTimer.Start();
}
Is there a better way to do this?
EDITED: Im using a simple query, like this:
string credentials = "Server=127.0.0.1;port=3306;Database=test;Uid=root;password=root;";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(credentials);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable;";
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//...
}
}
catch { }
finally { if (conn != null)conn.Close(); }
[SOLVED]
Well, i was reading the comments and i decided to investigate about await
which solved my problem.
I simply wrote this inside my "Timer Function" (TimerBackground):
private async void TimerBackground(Object myObject, EventArgs eventArgs)
{
// This prevents the GUI from freezing.
await Task.Run(() =>
{
runQueryFunction();
});
}