开发者

Using instances of one class in different threads

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 cla开发者_运维技巧ss 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 DBConnectionHelper class 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.


Yes, you can create separate instances of your class in separate threads without having any issues. Things get more complicated if you're accessing static classes/members from different threads, or sharing the SAME instance of your class between threads, but what you're doing is completely safe.

On a side note, you may want to avoid loading Entity Framework entities from your UI thread, as your UI will be unresponsive while your entities are being loaded from the database. That would be a good time to use a background worker thread or a Task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜