スレッドプーリングなどについて調べたところ、その例が見つかりました。現時点では、自分のプロジェクトで見た例を再作成しようとしていましたが、UI から数値を入力するとこのエラーが発生し続けます。
ManualResetEvent[] doneReadEvents = new ManualResetEvent[Read];
ManualResetEvent[] doneWriteEvents = new ManualResetEvent[Write];
ReadWrite[] ReadArray = new ReadWrite[Read];
ReadWrite[] WriteArray = new ReadWrite[Write];
for (int i = 0; i < Read; i++)
{
doneReadEvents[i] = new ManualResetEvent(false);
ReadWrite Rw = new ReadWrite(Read, doneReadEvents[i]);
ReadArray[i] = Rw;
ThreadPool.QueueUserWorkItem(Rw.ThreadPoolCallBackRead, i);
}
for (int i = 0; i < Write; i++)
{
doneReadEvents[i] = new ManualResetEvent(false);
ReadWrite rW = new ReadWrite(Write, doneWriteEvents[i]);
ReadArray[i] = rW;
ThreadPool.QueueUserWorkItem(rW.ThreadPoolCallBackWrite, i);
}
WaitHandle.WaitAny(doneReadEvents);
WaitHandle.WaitAny(doneWriteEvents);
temp.Items.Add("Complete");
temp.Items.Add("Closing");
Output.DataSource = ReadWrite.MyList;
Work.DataSource = ReadWrite.MyList2;
ReadWrite.ReadData(Read);
}
最初のループの最初の行で、配列の範囲外であるというエラーが表示されます。そのエラーが解消されると、さらにエラーが発生するかどうかわかりません
namespace MultiThreadingReaderWriter
{
class ReadWrite
{
public int _rw;
public ManualResetEvent _doneEvents;
public List<string> myList = new List<string>();
public List<string> myList2 = new List<string>();
public List<string> MyList{ get { return myList; } }
public List<string> MyList2{ get { return myList2; } }
public int RW { get { return _rw; } }
//Constructor
public ReadWrite(int rw, ManualResetEvent doneEvents)
{
_rw = rw;
_doneEvents = doneEvents;
}
public void ThreadPoolCallBackRead(Object threadContext)
{
int threadindex = (int) threadContext;
myList.Add("Thread Read " + threadindex+ " started");
ReadData(_rw);
myList.Add("Thread Read " + threadindex + " done");
_doneReadEvents.Set();
}
public void ThreadPoolCallBackWrite(Object threadContext)
{
int threadindex = (int)threadContext;
myList.Add("Thread Write " + threadindex + " started");
WriteData(_rw);
myList.Add("Thread Write " + threadindex + " done");
_doneWriteEvents.Set();
}
public void ReadData(int reader)
{
myList.Add("Reader " + reader + " has entered Critical Section");
myList.Add("Reader " + reader + " is Reading");
myList.Add("Reader " + reader + " is leaving Critical Section");
}
public void WriteData(int writer)
{
myList.Add("Writer " + writer + " has entered Critical Section");
myList.Add("Writer " + writer + " is writing");
myList.Add("Writer " + writer + " is leaving Critical Section");
}
}
}
これは、上記のフォーム プログラムに接続されたクラスです。