开发者

Should I add Locks or TransactionScope when using .Net Cache?

I’m using HttpContext.Current.Cache to cache data from the DB (.Net 4 web application).

I want to make sure I don’t run into any threading synchronization problem.

Scenario: 3 users pointing to the same Company Object:

User A:

开发者_JS百科Profile.Company.Name  = “CompX”;
Profile.Company.Desc  = “CompXDesc”;
Profile.Company.Update(); //Update DB

User B:

String Name = Profile.Company.Name;

User C:

Profile.Company.Name  = “CompY”;
Profile.Company.Update(); //Update DB

Questions:

  1. Does the Cache provide any type of locking?

  2. Should I add Locks like ReaderWriterLockSlim (how exactly)?

Existing Code:

ProfileBLL:
public CompanyBLL Company    {
        get        {
                return CompanyBLL.GetById(this.Company_ID);
        }
    }

// HttpContext.Current.Cache
public static CompanyBLL GetById(int Company_ID) {
        string key = "GetById_" + Company_ID.ToString();
        CompanyBLL ret = null;
        if (Cache[key] != null) {
            ret = (CompanyBLL)Cache[key];
        }
        else
        {
            ret = DAL_Company<CompanyBLL>.GetById(Company_ID);
            Cache[key] = ret;
        }
        return ret;
}

Another option is to add TransactionScope on any DB update:

User A:

using (TransactionScope Scope = new TransactionScope()){
Profile.Company.Name  = “CompX”;
Profile.Company.Desc  = “CompXDesc”;
Profile.Company.Update(); //Update DB
Scope.Complete(); //COMMIT TRANS
}

User B:

String Name = Profile.Company.Name;

Will it solve any threading problem?

Thanks


You have nothing to worry about. The class is thread safe.


If you're using SQL to store cache then SQL will lock the row as it's being written (under pessimistic mode, which is default) so you wont have to worry about that. Transactions aren't going to provide thread safety but you should do it anyway when making changes that need to be consistent.

You can always add a lock around any "write" methods you have.

If you want to make sure that when any user calls a "read" method that they get the absolute latest then put a lock around those methods as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜