将数组分配给另一个数组

将数组分配给另一个数组

本文介绍了C#:将数组分配给另一个数组:复制还是指针交换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉提出这个问题,我已经在Google搜索了一下,但是看来出现的是对克隆或复制方法的引用,而不是C#中我问题的实际答案.

Sorry for asking this question, I have been Googling a bit but it seems what comes up is references to clone or copy methods, not an actual answer for my question in C#.

我有两个字节数组,两个线程正在访问它们.

I have two arrays of bytes, and they are being accessed by two threads.

private byte[] buffer1 = new byte[size];
private byte[] buffer2 = new byte[size];

我的目标是在Thread1中的buffer1中编写,获取互斥锁,切换指针并重复该过程. Thread2会抓住一个互斥锁并始终读取buffer2.

My goal is to write in buffer1 in Thread1, grab a mutex, switch the pointers around and repeat the process. Thread2 would grab a mutex and always read buffer2.

目标是Thread2快速运行,并且不受Thread1中进行的复制的影响.

The goal is that Thread2 runs fast and is not affected by the copy taking place in Thread1.

我不清楚执行以下操作会发生什么情况:

I am very unclear what happens when I do the following:

byte[] temp = buffer1;
buffer1 = buffer2;
buffer2 = temp;

是切换指针还是将buffer2的内容复制到buffer1?这应该是一个简单的问题,但我似乎找不到解决方案. Thread1正在执行Marshal.Copy(),我不希望通话影响Thread2.

Are the pointers being switched or is the content of buffer2 being copied to buffer1? It should be a simple question but I can't seem to find the solution. Thread1 is doing a Marshal.Copy(), and I don't want the call to impact Thread2.

推荐答案

赋值总是只将一个表达式的值复制到变量中(或调用属性/索引设置器).

Assignment always just copies the value of one expression into a variable (or calls a property/indexer setter).

以您的情况为例,

buffer1 = buffer2;

... buffer2的值只是对字节数组的引用.因此,在完成该赋值后(假设没有其他赋值),对字节数组"via"进行的更改将在另一个变量"via"中可见.

... the value of buffer2 is just a reference to a byte array. So after that assignment (and assuming no other assignments), changed made to the byte array "via" one variable will be visible "via" the other variable.

这不是特定于数组类型的-这是引用类型一直通过.NET起作用的方式:

This isn't specific to array types - this is how reference types work all the way through .NET:

StringBuilder x = new StringBuilder();
StringBuilder y = x;
x.Append("Foo");
Console.WriteLine(y); // Foo

只需了解数组始终是引用类型即可.

It's just a matter of understanding that arrays are always reference types.

这篇关于C#:将数组分配给另一个数组:复制还是指针交换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:42