The foundation is the top priority ~ Threadstatic static field uniqueness in each thread

Source: Internet
Author: User

Back to directory

Static modifiers are not new to us. They represent static and can be used to modify your classes, methods, fields, and attributes. Today, we mainly say that the threadstatic feature for static fields will giveProgramWhat kind of changes come from. Static field, which is more often called a "class field", that is, it has nothing to do with a specific instance of the class. For a wired field, its value is one, that is, its uniqueness.

For exampleCode:

 
ClassInstance
{Static DatacontextContext =New linqtosql (conn );
ProtectedStatic Datacontext{Get {return context ;}}
}

In the above Code, context is a static field, and its values are the same in all threads. In other words, when multiple users access a page, their values are the same.

The above code is a base class for implementing the Dal layer in a LINQ to SQL statement. It exposes a data context to the subclass and the value (memory address) of the data context during all user access (in all threads) in the linqtosql architecture,This static data context may cause many problems in implementation and development.Therefore, it is not officially recommended.

However, if we introduce threadstatic, the results will be different. When the field is modified by the threadstatic feature, its values will be different in each thread, that is to say, each thread will re-allocate the memory space for the static field, and of course it will be in a new operation. As a result, the problems caused by the static field will no longer exist, this static data context is acceptable.

     Internal   Class  Dbfactory {  # Region Fields ///   <Summary>          ///  Each thread, a new datacontext instance ///   </Summary>  [Threadstatic]  Static   Readonly Datacontext current = New  Dataclasses1datacontext ();  # Endregion          # Region Contructors # Endregion          # Region Properties Public   Static Datacontext current {  Get { Return  Current ;}}  # Endregion          # Region Methods # Endregion          # Region Events # Endregion  } 

The above code is a factory that generates the LINQ context. You can create a base class for each linqtosql class to obtain the context, and the specific operation class inherits the base class, in Microsoft's architecture,

It is very common, such as system. Web. MVC. controllerbase, which is the base class of controller.

 ///  <Summary>      ///  Dataclasses1datacontext database base class  ///   </Summary>      Public   Abstract   Class  Dbbase {  # Region Fields # Endregion          # Region Contructors # Endregion          # Region PropertiesPublic Dataclasses1datacontext DB = dbfactory. Current As  Dataclasses1datacontext;  # Endregion          # Region Methods # Endregion          # Region Events # Endregion  } 

For specific table curd operations, you can create a class file separately to do this.

 Public   Class  Webmanageusers_ext: webmanageusers {}  Public  Class  Userdal: dbbase {  # Region Fields # Endregion          # Region Contructors # Endregion          # Region Properties # Endregion          # Region Methods Public Iqueryable <webmanageusers> GetModel (){  VaR LINQ = From Data1 In   Base  . DB. webmanageusers join data2  In   New  Deptdal (). GetModel () on data1.20.mentid equals data2.20.mentid  Select   New  Webmanageusers_ext {realname = Data1.realname, webscripts = Data2 ,}; Return  LINQ ;}  # Endregion          # Region Events # Endregion  } 

OK. If the above Code is output, the result is correct.

In fact, for the complex query I used above, if your data context is not of the static type, it will cause an exception, generally, the exception is "cannot handle reference of different data contexts". Of course, this prompt is normal, because if your context is an instance object, then for each class, it is all different and will be new once!

When the above problem occurs, we often solve the problem by using the static context, while the static type itself is problematic in linqtosql. During the data update operation, all threads, all operations have one LINQ cache. When submitchange is performed,There will be confusion, and errors are unpredictable.. Therefore, you have to write all the table link queries in the Dal layer and rewrite the complex query methods of each business once.No data contextThe problem is terrible.

Of course, if you associate a table in advance, using the "load now" method of LINQ is also a good method. It can save a lot of code, but it produces SQL statements, the query is in the select * from table format, that is, many useless columns are returned.

To sum up, the only static data context of a thread is the best solution!

Back to directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.