Yikes! Don't you guys make voting machines?
Your surmise is correct, what you've posted won't work.
You have two main approaches.
1) System.Threadin g.Interlocked.I ncrement is an atomic (and therefore
somewhat thread-safe) operation.
2) Have a private locking object; this will allow more complex atomic
operations.
int Votes;
Object Locking; // = new Object(); in the constructor
void PlaceVote()
{
__try // In case you're going to do something that might throw.
{
Monitor::Enter( Locking );
// NB Don't use Enter( this ) or Enter( typeof(...) )
++Votes;
}
__finally
{
Monitor::Exit( Locking );
}
}
C# has a shortcut for this pattern, namely the lock statement.
Hope that helps,
Stu
"Ken Varn" <nospam> wrote in message
news:%2******** ********@TK2MSF TNGP12.phx.gbl. ..
If I have a value type such as int that I want to protect in a
multi-threaded situation, Is it safe to use Monitor::Enter( __box(value))?
I am thinking that a different object pointer is generated each time and
thus the protection is not insured. Is this true or not?
Example:
public _gc class MyClass
{
int Value;
void IncValue()
{
Monitor::Enter( __box(Value));
Value++;
Monitor::Exit(_ _box(Value));
}
};
--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.
EmailID = varnk
Domain = Diebold.com
-----------------------------------