Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have use the parallel.invoke method and in which 2 method are present which increment the common variable.

int cnt=0;

parallel.invoke(
()=>method1,
()=>method2
);

public void method1()
{
cnt++;
}
public void method2()
{
cnt++;
}

What I have tried:

I have use the Volatile for variable
I have used Interlocked.increment but not able to resolve
Posted
Updated 4-Jul-18 5:21am

1 solution

When you show us code, show us what you actually tried - that wont; compile for a large pile of reasons!

The most likely reason it doesn't work is that cnt is a local variable to the method in which you are calling Parallel.Invoke.
If you correct your compiler errors (and add some logging statements) it works just fine:
namespace GeneralTestingConsole
    {
    class SampleClass
        {
        static int cnt = 0;
        public static void Main()
            {

            Parallel.Invoke(
            () => method1(),
            () => method2()
            );
            Console.WriteLine(cnt);
            }

        public static void method1()
            {
            Console.WriteLine("1:{0}", cnt);
            cnt++;
            Console.WriteLine("1={0}", cnt);
            }
        public static void method2()
            {
            Console.WriteLine("2:{0}", cnt);
            cnt++;
            Console.WriteLine("2={0}", cnt);
            }
        }
    }

1:0
2:0
2=2
1=1
2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900