我对 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");
}
}
这是做什么(或至少应该做什么)是获取“文档”对象的数组,并为每组 3 个数组启动 3 个线程,然后等待它们完成生成那些 WebDAV PUT 请求。这只是为了测试线程而编写的非常粗略的代码,但我认为在这种状态下它仍然很好。