Search code examples
c#async-awaitmaui

How to open database connection asynchronously?


If connection times out, I see the error message, but the page with all the messages shows up only after the timeout. How to make the page show up at once and show "Opening database connection" before trying to connect?

public partial class MainPage : ContentPage
    public MainPage()
        {
            InitializeComponent();

            try
            {
                ServerName.Text = "Opening database connection"; // ServerName is a label
                sqlclient.sqlconnection conn = new();
                conn.connectionstring=... // assume I initialized it
                conn.open
                ServerName.Text += "\nOpened successfully"; 
            }
            catch (Exception ex) {
                ServerName.Text += $"\n{ex.Message}"; 
            }
}

Solution

  • This should work. Call this from the Page/Window Loaded Event

       public MainPage()
       {
           InitializeComponent();
           MainPage.Loaded += async (sender, e) =>
           {
             try
             {
                await Task.Run(() =>
                {
                    ServerName.Text = "Opening database connection";
                    // ServerName is a label
                    sqlclient.sqlconnection conn = new();
                    conn.connectionstring = "ConnectionString"; // assume I initialized 
                    conn.open();
                    ServerName.Text += "\nOpened successfully";
                    // do Some Operation 
                    conn.close();
                });
             }
             catch (Exception ex)
            {
                ServerName.Text += $"\n{ex.Message}";
            }
        };
      }