I am porting code from a managed c# project to a mixed mode C++/CLI project this week. I ran across this construct in some c# code:
lock (this)
{
this->m_internalCounter++;
}C++/CLI does not have a lock statement. A little research and some decompilation showed that the Monitor class should suffice. After I learned how the lock statement worked, I thought the small block of code was interesting. Why? The entire instance of the class is locked in order to update a single counter. (Or at least it looks this way to me.)
The nearly equivalent way to do this in C++/CLI is using the
Monitor class.
// lock (this)
{
Monitor::Enter(this);
this->m_internalCounter++;
Monitor::Exit(this);
}I've left the brackets and commented out
lock statment in place so you may visualize the code changes necessary. The object that Monitor.Enter acts on is flexible, and I want to test Monitor.Enter with the
m_internalCounter variable, instead of locking the entire instance of the class. I like to code in C++/CLI, but I am no expert on managed threads and locking, so it will take some testing to determine if Monitor.Enter will lock on a variable in an instance of a class. I wonder if this counts as
codinghorror practice?
Part 2 of the
c# lock statement.