C # Connecting to a database in a separate thread

I have an application that is located on the taskbar and periodically checks the database (via SQLConnection). If the database is not available, it simply displays a red status on the notification icon and nothing else. This is necessary, since users will be on laptops traveling between objects, and the database is only available on the internal network or when connecting via VPN.

The problem I am facing is that when the database is not available, I will still like the context menu of the notification icon. Currently, if a user tries to interact with the menu when the database tries to connect, the thread is blocked when trying to connect.

I want the database connection to occur in a separate thread, but I know that sharing a connection object between threads is bad, which is to try. Once the database is connected, I need to request it from the source stream. Is there a good way to do this?

I know that I could have the rus function in a new thread and just checks to see if the connection is completed or not, then if this returns success, the original thread can go over and associate it with its own database object. But this method seems like a bad workaround. Ideas?

Thank!


Thanks for the suggestions - I learned a little from them. In the end, I did what I had to do from the very beginning. The main (UI) thread simply starts a new thread (which includes creating and connecting the database object) whenever a periodic database update is required.

So, as suggested by HenkHolterman in a comment on my original post, I really did not need to create a database and start operations with it in separate threads.

I will definitely be interested in using SqlConnection.OpenAsync as soon as I upgrade to VS2010.

Thanks again.

+5
source share
3 answers

A SqlConnection , . , .

Task (System.Threading.Task), , ContinueWith, .

public class TrayIconForm : Form
{
  private SqlConnection connection = null;

  private void Form_Load(object sender, EventArgs args)
  {
    TaskScheduler ui = TaskScheduler.FromCurrentSynchronizationContext();

    Task.Factory.StartNew(() =>
      {
        var sql = new SqlConnection();
        sql.ConnectionString = "your connection string";
        sql.Open();
        return sql;
      }).ContinueWith((task =>
      {
        connection = task.Result;
        // You can access other UI elements here as needed.
      }), ui);
  }
}

async await , # 5.0 Async CTP, .

private async void Form_Load(object sender, EventArgs args)
{
  connection = await Task.Run(() =>   // TaskEx.Run in the CTP
    {
      var sql = new SqlConnection();
      sql.ConnectionString = "your connection string";
      sql.Open();
      return sql;
    });
}
+6

Using the BackgroundWorker object should solve your problem in a simple way, although more precisely you want to use streams to try to open the connection, leaving the UI thread ready to accept user input.

+1
source

All Articles