title: C# Connect to database in separate thread
body: <p>I have an application that sits in the taskbar and periodically checks a database (via SQLConnection).  If the database is unreachable, it just shows a red status on the notify icon, and nothing else.  This is intended since the users will be on laptops traveling between facilities, and the database is only reachable on an internal network or when connected via VPN.</p>
  
  <p>The issue I'm having is that when the database is unreachable, I'd still like the notify icon context menu to be responsive.  Currently if the user tries to interact with the menu while the database is attempting to connect, the thread is locked up with the connection attempt.</p>
  
  <p>What I'd like is for the database connection to happen in a separate thread, but I know that sharing the connection object between threads is a bad thing to try to do.  Once the database has connected, I need to query it from the original thread.  Is there any good way to do this?</p>
  
  <p>I know that I could have a function that rus in a new thread and simply checks if the connection fails or not, then if that returns success the original thread could move on and connect it's own database object.  But that method seems like a bad workaround.  Ideas?</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Thanks for the suggestions - I have learned quite a bit from them. In the end, I did what I should have done from the start. The main (UI) thread just kicks off a new thread (which includes database object creation and connection) whenever a periodic database update is needed.</p>
  
  <p>So, like HenkHolterman suggested in a comment to my original message, I really did not need to create the database and run operations with it in separate threads.</p>
  
  <p>I will definitely be interested in using SqlConnection.OpenAsync once I've made the upgrade to VS2010.</p>
  
  <p>Thanks again.</p>