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

Im uses HttpContext.Current.Cache to cache data from the database (.Net 4 web application).

I want to make sure that I am not facing any thread synchronization issue.

Scenario: 3 users pointing to the same company object:

User A:

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:

  • Does the cache provide any type of lock?

  • Should I add locks like ReaderWriterLockSlim (exactly how)?

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 to any database 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 any problem with threads be solved?

thank

+3
source share
2 answers

. .

+1

SQL , SQL , ( ), . , , .

.

, , - "read", , .

0

Source: https://habr.com/ru/post/1794141/


All Articles