8

I am creating some custom performance counters. I will be creating tasks on a thread pool and incrementing/decrementing the counters from within multiple worker threads.

Do I need to give each thread a new counter object? Is it safe to share a performance counter object cross-thread (for increment/decrement)

JMarsch
  • 21,484
  • 15
  • 77
  • 125

1 Answers1

6

The PerformanceCounter class already uses a threadsafe wrapper, an internal class named SharedPerformanceCounter. It uses Interlocked.Increment() to increment a counter value for example.

There's no need to lock yourself.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Yah, I ended up reflectoring in there and saw that. Then I read the help, and it reads that only the static methods are thread safe. So, I guess now I'm stuck with a philosophical dilemma: Since the documentation doesn't guarantee safety, should I treat the current wrapper as an implementation detail, ignore it, and create thread-specific instances, or should I treat it as a documentation error and proceed with shared counters? given what I see in the code, I think I'm safe, but 15 years of software engineering has jaded me, so I might go conservative. – JMarsch Jan 14 '10 at 15:49
  • If you want a guarantee with a warranty you'll need to call Microsoft. – Hans Passant Jan 14 '10 at 15:59
  • Yah, I know, I'm not expecting that here. Just sounding out what I'm thinking. – JMarsch Jan 14 '10 at 17:51