. NET static variable and static method concurrency problem

Source: Internet
Author: User

We know that both static and static methods are defined when the program compiles, and there are no more than one copy. So for static variables, once modified, it will affect the global.

Therefore, the static variable is a concurrency problem, so when we are operating static variables need to take into account the concurrency problem, in general, we use the "lock" operator, add a mutex is OK, as follows:

lock(obj )//Random New Object
{
In this case, you can manipulate static variables.
}

For a static method, it's just some code that handles logic, and no matter how many individuals are manipulating it, it doesn't change itself.      Therefore, if you do not manipulate other static variables in a static method, There is no concurrency problem.

There may be another question: Is there a concurrency problem with local non-static variables in static methods?

The answer is no, because the method itself, although there is only one copy, but in the execution process, the local variables are dynamically allocated, the same static method in the same name variable, when the static method executes concurrently, the address in memory is not the same, and therefore does not affect each other.

. NET static variable and static method concurrency problem

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.