私は c# とマルチスレッドの両方に不慣れで、最近、私が書いているツールで少し障害にぶつかりました。このツールは、多数の HttpWebRequest を生成して起動するように設計されています。現在、シングル スレッドで問題なく動作していますが、タスクを 3 つほどのワーカー スレッドに分割し始めるとすぐに、プログラムがクラッシュし、次のメッセージが表示されます。
「vshost32-clr.exe が動作を停止しました」
これらのスレッドを作成する方法と関係があるのでしょうか?
これが私が使用しているC#コードスニペットです。これを少し手抜きにしないための推奨事項は大歓迎です。
private void CreateDocuments()
{
int docCount = 0;
ArrayList vsIDs = docRepo.GetVersionIDList();
ArrayList versionList = new ArrayList();
foreach (string vsID in vsIDs)
{
Document[] docs = docRepo.GetVersionSeries(vsID);
versionList.Add(docs);
if (versionList.Count == 3)
{
Console.WriteLine("Launch Thread");
Document[] docs1 = (Document[])versionList[0];
Document[] docs2 = (Document[])versionList[1];
Document[] docs3 = (Document[])versionList[2];
Worker w1 = new Worker(docs1);
Worker w2 = new Worker(docs2);
Worker w3 = new Worker(docs3);
Thread t1 = new Thread(new ThreadStart(w1.Start));
Thread t2 = new Thread(new ThreadStart(w2.Start));
Thread t3 = new Thread(new ThreadStart(w3.Start));
Console.WriteLine("Threads Started");
t1.Start();
t2.Start();
t3.Start();
//Wait until all threads have started
while (!t1.IsAlive || !t2.IsAlive || !t3.IsAlive) { Console.WriteLine("Waiting for Threads to Start"); }
Console.WriteLine("Wait on Threads");
t1.Join();
docCount += docs1.Length;
t2.Join();
docCount += docs2.Length;
t3.Join();
docCount += docs3.Length;
log.Info(docCount + " Documents Imported");
versionList.RemoveRange(0, 3);
}
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
public class Worker
{
ImportToolWebDAV itwd = new ImportToolWebDAV();
Document[] docs;
public Worker(Document[] _docs)
{
docs = _docs;
}
public void Start()
{
HttpStatusCode status = HttpStatusCode.OK;
foreach (Document doc in docs)
{
status = itwd.createDocument(doc);
}
Console.WriteLine("Thread finished");
}
}
これが行っていること (または少なくとも行うべきこと) は、"Document" オブジェクトの配列をフェッチし、3 つの配列のセットごとに 3 つのスレッドを起動し、それらが WebDAV PUT 要求の生成を完了するのを待機することです。これはスレッドアウトをテストする目的で書かれた非常に大雑把なコードですが、この状態でも問題ないと思いました。