Saturday, February 19, 2011

How to use System::Threading::Interlocked::Increment on a static variable from C++/CLI?

I would like to keep a static counter in a garbage collected class and increment it using Interlocked::Increment. What's the C++/CLI syntax to do this?

I've been trying variations on the following, but no luck so far:

ref class Foo
{
   static __int64 _counter;

   __int64 Next()
   {
      return System::Threading::Interlocked::Increment( &_counter );
   }

};
From stackoverflow
  • You need to use a tracking reference to your _int64 value, using the % tracking reference notation:

    ref class Bar
    {
        static __int64 _counter;
    
        __int64 Next()
        {
         __int64 %trackRefCounter = _counter;
         return System::Threading::Interlocked::Increment(trackRefCounter);
        }
    };
    

0 comments:

Post a Comment