【发布时间】:2011-02-25 18:27:24
【问题描述】:
这是我正在尝试做的一个非常简化的版本
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(); //Writes 1 should write 1
B.write(); //Writes 1 should write 2
C.write(); //Writes 1 should write 1
Console.ReadLine();
}
class Test
{
int _a;
public Test(ref int a)
{
_a = a; //I loose the reference here
}
public void write()
{
var b = System.Threading.Interlocked.Increment(ref _a);
Console.WriteLine(b);
}
}
在我的真实代码中,我有一个 int,它将被许多线程递增,但是在线程 a 调用的情况下,将指向它的参数传递给它并不容易 int(在实际代码中,这发生在 a IEnumerator)。所以一个要求是必须在构造函数中进行引用。此外,并非所有线程都指向同一个基 int,因此我也不能使用全局静态 int。我知道我可以将 int 封装在一个类中并传递该类,但我想知道这是否是执行此类操作的正确方法?
我认为可能是正确的方法:
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(); //Writes 1 should write 1
B.write(); //Writes 2 should write 2
C.write(); //Writes 1 should write 1
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);
}
}
还有比这更好的方法吗?
【问题讨论】:
标签: c# pass-by-reference