私が理解している限り、参照型をメソッドのパラメーターとして使用すると、スタック上の値がコピーされ、仮パラメーターはヒープ上の元と同じメモリアドレスを指すため、変更されますメソッドを終了すると、永続化されます。
これはタスクでどのように機能しますか? 2 つの新しいタスクを作成し、UI スレッドで宣言された配列を渡しました。新しいタスクの 1 つで行われた変更は、すぐに 2 番目のタスクに表示されました。UI スレッドを介して入力 (配列) を変更しようとすると、2 つの新しいタスクで同じパラメーターが変更されません。それらはすべてヒープ上の同じメモリ位置を指しているはずなので、私はそれがあるべきだという印象を受けました??
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TasksAndMemory
{
class Program
{
private static ManualResetEvent mre = new ManualResetEvent(false);
static void Main(string[] args)
{
int[] readToEnd = new int[2];
int[] data = new int[] { 1, 2, 3, 4, 5, 6 };
int valueType = 5;
int pageCounter = 1;
Task[] tasks = new Task[2];
for (int x = 1; x < 3; x++)
{
//Needed due to closure problem
int i = x;
tasks[i-1] = Task.Factory.StartNew(() =>
{
SpecialMethod(data, readToEnd, i, valueType);
});
}
while(pageCounter < 4)
{
if (readToEnd[0] == 1 && readToEnd[1] == 1)
{
//Sets the state of the event to nonsignaled, causing threads to block
mre.Reset();
int[] temp = new int[] { 7, 8, 9, 10, 11, 12 };
data = temp;
readToEnd[0] = 0;
readToEnd[1] = 0;
//Sets the state of the event to signaled, allowing one or more waiting threads to proceed.
mre.Set();
pageCounter++;
}
}
Console.ReadLine();
}
public static void SpecialMethod(int[] historicalData, int[] readToEnd, int taskNumber, int valueTy)
{
int[] temp = new int[] { 100, 200, 300, 400, 500, 600 };
for (int x = 0; x <= historicalData.Length; x++)
{
if (x == historicalData.Length)
{
readToEnd[taskNumber-1] = 1;
mre.WaitOne();
x = 0;
}
else
{
valueTy++;
temp[x] = temp[x] + taskNumber;
}
}
}
}
}