我使用了parallel.invoke方法,其中存在2个方法,它增加公共变量,但不增加变量 [英] I have use the parallel.invoke method and in which 2 method are present which increment the common variable but it is not increment the variable

查看:59
本文介绍了我使用了parallel.invoke方法,其中存在2个方法,它增加公共变量,但不增加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了parallel.invoke方法,其中存在2个增加公共变量的方法。



int cnt = 0;



parallel.invoke(

()=>方法1,

()=>方法2

);



public void method1()

{

cnt ++;

}

public void method2()

{

cnt ++;

}



我尝试过:



我使用Volatile变量

我使用了Interlocked.increment但无法解析

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

推荐答案

当你向我们展示代码时,告诉我们你实际尝试了什么 - 那不会;编译有很多原因!



最不可能的原因是cnt是你调用Parallel的方法的局部变量。调用。

如果你纠正了你的编译器错误(并添加了一些日志记录语句),它的工作正常:

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


这篇关于我使用了parallel.invoke方法,其中存在2个方法,它增加公共变量,但不增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆