Here is a very simplified version of what I'm trying to do
static void Main(string[] args)
{
int test = 0;
int test2 = 0;
Test A = new Test(ref test);
Test B = new Test(ref test);
Test C = new Test(ref test2);
A.write();
B.write();
C.write();
Console.ReadLine();
}
class Test
{
int _a;
public Test(ref int a)
{
_a = a;
}
public void write()
{
var b = System.Threading.Interlocked.Increment(ref _a);
Console.WriteLine(b);
}
}
In my real code, I have an int that will increase by many threads, however, when the threads a, called it, will not easily pass a parameter to it that points it to int (In real code, this happens inside IEnumerator). Therefore, the requirement must be made in the constructor. Also, not all threads will point to the same base int string, so I cannot use a global static int. I know that I can just insert an int inside the class and pass the class, but I wanted to know if it is right to do something like this?
What I think may be correct:
static void Main(string[] args)
{
Holder holder = new Holder(0);
Holder holder2 = new Holder(0);
Test A = new Test(holder);
Test B = new Test(holder);
Test C = new Test(holder2);
A.write();
B.write();
C.write();
Console.ReadLine();
}
class Holder
{
public Holder(int i)
{
num = i;
}
public int num;
}
class Test
{
Holder _holder;
public Test(Holder holder)
{
_holder = holder;
}
public void write()
{
var b = System.Threading.Interlocked.Increment(ref _holder.num);
Console.WriteLine(b);
}
}
Is there a better way than this?