Open a database connection asynchronously

HomeC#

Open a database connection asynchronously

Case insensitive comparison in C#
Return output slowly in C#
How to use oAuth 2.0 in C#

C# allows opening database connections asynchronously, but there are a couple things to take in consideration, you need to close the connection otherwise when you’re done the variable will be out of scope and you won’t be able to close it. Also remember to not do async on voids, only on event handlers.

The following code should take care of things


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}";
        }
    };
  }

COMMENTS

DISQUS: 0