线程c#的数组副本

时间:2016-08-31 07:40:19

标签: c# arrays multithreading asynchronous

我遇到了麻烦,我有一个每隔近200毫秒执行一次的循环并填充2个阵列,一个是旧的一个副本,另一个是新的。

这是循环代码:

private byte[] _oldBuffer;
private byte[] _newBuffer;

private void Cycle()
{
   while(exitCondition)
   {
     //do other stuff that not involved _newBuffer or _oldBuffer
     GetNewBuffer()
     //other stuff that not involved _newBuffer or _oldBuffer too
     Thread.Sleep(200); //or more, minimum 200
   }
}

private void GetNewBuffer()
{
        _oldBuffer = _newBuffer;

        //retrieve from PLC the new buffer
        _newBuffer = RetrieveNewBuffer();

        Thread checkDifference = new Thread(() => MethodToCall.Start(_oldBuffer, _newBuffer));
        checkDifference.Start();

}

这里是Thread执行的方法

public static void Start(byte[] oldBuffer, byte[] newBuffer)
{
    for(int i = 0; i < oldBuffer.Lenght; i++)
    {
        //here happens that the two buffer are equal even if at starting the process they weren't
        //they could be equal from a read to another, not always something change every 200ms
        if(oldBuffer[i] != newBuffer[i])
            //value has change, handle method
    }        
}

我的问题是,在下一次阅读中我会覆盖_oldBuffer和_newBuffer,并且线程会抓住它们进行修改,并且不会发现两者之间存在差异(或者至少这是我从调试中得到的),没有更多不同的阵列。

有什么建议吗?

感谢任何人的建议

1 个答案:

答案 0 :(得分:0)

我尝试使用Array.Copy()并且它可以工作,数组没有被更改。这样的事情:

private void GetNewBuffer_ArrayCopy()
{
        _oldBuffer = _newBuffer;
        _newBuffer = RetrieveNewBuffer();

        byte[] localOldBuffer = new byte[_oldBuffer];
        Array.Copy(_oldBuffer, localOldBuffer, 0);
        byte[] localNewBuffer = new byte[_oldBuffer];
        Array.Copy(_newBuffer, localNewBuffer, 0);

        Thread checkDifference = new Thread(() => MethodToCall.Start(localOldBuffer, localNewBuffer));
        checkDifference.Start();

}