tags:

views:

62

answers:

2

I pass a data access class (DAL) of my own making into a another class so it can use those data access methods to store data in my sqlite database.

This is type-safe because each method that accesses the database creates it's own connection object so calls to the connection object always come from the same thread it was created on.

I'd like to just use one connection (or a pool of connection objects) in my DAL class and this would work fine if all calls to my DAL came from the main UI thread.

Is there a way for my DAL class to use a connection object (or pool of them) when called from the main thread but then use a different connection object if is being called from a background thread?

+5  A: 

You can call InvokeRequired on any WinForms Control-derived type to determine if you're on the main thread or not. If InvokeRequired returns true, then you are not on the main UI thread.

If you're using WPF, you can call Dispatcher.CheckAccess on the DependencyObject.Dispatcher property of one of your UI elements. If CheckAccess returns true, it's the main UI thread.

Jeff Yates
Handily, my DAL object inherits from a plugin that is also a control. Thanks!
Neil Trodden
+1  A: 
if (!mainForm.InvokeRequired)
{
    // running on the UI thread
}
else
{
    // running on a different thread
}

(you can use any control instead of mainForm)

Thomas Levesque