Mysql database freezes with Visual Sudio C#

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10
I a'm reading values from raspberry pi mysql database with visual studio c#
If the database is not available and I am trying to read from it, the c# app
freezes for about 15 seconds.

Is it possible to make it not to freeze when checking if the database is available?

Her is the code


C#:
string connString = "SERVER='192.168.86.41';DATABASE='spaceinformation';UID='******';PASSWORD='******'";
 private void FormMeasurement_Load(object sender, EventArgs e)
        {
            try
            {
                using (var connection = new MySqlConnection(connString))
                {
                    connection.Open();

                    query = "select * from weather";
                    using (var command = new MySqlCommand(query, connection))
                    {
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                listBoxMeasurement.Items.Add(string.Format("Temperature: {0}   Humidity: {1}   Date: {2}", reader.GetString("temp"), reader.GetString("hum"), reader.GetString("datecreated")));
                            }
                        }
                    }
                    connection.Close();
                }
            }
            catch
            {
                MessageBox.Show("Database is not available for moment!");
                listBoxMeasurement.Enabled = false;
            }
        }
 
Yes. Don't put that code in the UI thread. Do all your work on a BackgroundWorkerThread thread; or a thread pool thread via async/await with Task.Run(); or explicitly queuing work on a thread pool thread.
 
install Dapper or EFCore and await one of their ...Async methods to do your read.

All that code you've written would come down to perhaps something like:

C#:
  try{
    var r = await db.Weather.ToArrayAsync();
    listBoxMeasurement.Items.AddRange(r);
  } catch {
   
    MessageBox.Show("Database is not available for moment!");
    listBoxMeasurement.Enabled = false;
  }

Note: your weather class should have an override of ToString that looks like:

C#:
    public override string ToString() => $"Temperature: {Temp}   Humidity: {Hum}   Date: {DateCreated}";

Note2: strive to avoid downloading the entire db into the client; especially something like weather, where there quickly become millions of readings
 

Latest posts

Back
Top Bottom