I’d like to make things more clear to me about using instances of a class in multithreading application:
Can I use instances of one and the same class in different threads? In other words, can I create in different threads instances of the same class?
For example:
I have a class DbConnectionHelper which gets a connection string in its default constructor and make the connection string visible using a public property:
public class DbConnectionHelper
{
string connstring;
public DbConnectionHelper()
{
string userconnstring = Settings.Default.ConnectionString;
connstring = GetConnectionString(userconnstring);
...
}
public string ConnString
{
get
{
return connstring;
}
set
{
connstring = value;
}
}
...
Then I have a number of repository classes which get data from a database using Entity Framework. Some of those repository classes have instances in UI thread, some of them – in other threads (not UI).
Can all of those repository classes get the connection string by creating instance of one class DbConnectionHelper and then reading its ConnString property?
DBConnectionHelper connhelper = new DBConnectionHelper();
string conn = connhelper.ConnString;
Separate instances of the same class are independent and share no common data, unless they all have a dependency to to a common object (such as a static variable in the class or a reference to another object that is the same for all or at least some instances).
In your case this is not a problem at all – you create an isolated instance of the
DBConnectionHelperclass each time you need it and use it just for building a connection string. You only have to worry about thread safety if multiple threads try and access methods of a shared object.