1

the code looks like this:

public class JobManager
{
    public static void TrackExceptionCount(ref int exceptionCount)
    {
        Interlocked.Increment(ref exceptionCount);
    }

    //other helper methods
}

I will call this method in other place like:

private static int _exceptionCount;

JobManager.TrackExceptionCount(ref _exceptionCount);

I thought Interlocked.Increment will handle the thread-safe problem, right?

Edit:

I have multiple Job class like this:

class JobA
{
    private static int _exceptionCount;

    public void method1()
    {
       Task.Factory.Start(()=>{
         try
         {
             //Some code
         }
         catch(exception ex)
         {
            JobManager.TrackExceptionCount(ref _exceptionCount);
         }
       });
    }

    public void method2()
    {
       Task.Factory.Start(()=>{
         try
         {
             //Some code
         }
         catch(exception ex)
         {
            JobManager.TrackExceptionCount(ref _exceptionCount);
         }
       });
    }
}

class JobB
{
    private static int _exceptionCount;

    public void method1()
    {
       Task.Factory.Start(()=>{
         try
         {
             //Some code
         }
         catch(exception ex)
         {
            JobManager.TrackExceptionCount(ref _exceptionCount);
         }
       });
    }

    public void method2()
    {
       Task.Factory.Start(()=>{
         try
         {
             //Some code
         }
         catch(exception ex)
         {
            JobManager.TrackExceptionCount(ref _exceptionCount);
         }
       });
    }
}

I believe that direct call Interlocked.Increment in the catch block probably a better way.

But still want to know if the JobManager.TrackExceptionCount(ref _exceptionCount) will be working probably, or not

Thanks.

Jeff Chen
  • 736
  • 1
  • 8
  • 20
  • No, the *static* keyword ruins your day. Interlocked might work, but of course your code snippet is entirely inadequate to see where else it gets used. – Hans Passant Nov 27 '12 at 00:22
  • Do you have any evidence that doing this is not thread-safe? Have you had any errors? Or are you just trying to confirm or deny your suspicions? – Enigmativity Nov 27 '12 at 00:25
  • Hi Enigmativity, I just met a case similar like this, so want to confirm or deny this suspicions. – Jeff Chen Nov 27 '12 at 00:34
  • Hi @JeffChen - you need to use the @ notation to ensure a notification gets sent. It was just luck that I checked this question again. – Enigmativity Nov 27 '12 at 01:40

1 Answers1

0

Assuming that your call to Interlocked.Increment is the only usage of the storage location _exceptionCount this is safe. You can pass ref parameters around safely. They work a little like a managed pointer to to variable (internally, they are).

usr
  • 168,620
  • 35
  • 240
  • 369