使用WebRequest的C#多线程程序

Old*_*ter 3 c# xml multithreading soap thread-safety

首先,我是论坛的新人,所以请耐心等待我和我的英语.:-)

我正在编写一个C#应用程序,它应该将多线程SOAP请求发送到apache后端.到目前为止,一切都很好,但我遇到了一个问题.应用程序首先从另一个系统读取XML文件,该系统首先被解析为类,然后排序并发送到SOAP后端.这里的片段

List<Thread> ThreadsPerOneRecord = new List<Thread>();         
bool ExecuteSingleThreaded = false;
//The variable list is passed as parameter to the function 

foreach (Record prov in list)
{
  XMLResult.AppendText("Type: " + prov.Type + Environment.NewLine);

  Thread t = new Thread(() => Send(prov, c));                                
  t.Start();
  //Here the sleep 
  Thread.Sleep(50);
  ThreadsPerOneRecord.Add(t);               

  #region Code for test single threaded execution
  if (ExecuteSingleThreaded)
  {
    foreach (Thread t2 in ThreadsPerOneRecord)
      t2.Join();
    ThreadsPerOneRecord.Clear();
  }
  #endregion
}

XMLResult.AppendText("Waiting for the threads to finish" + Environment.NewLine);
//Waiting for the threads to finish
foreach (Thread t in ThreadsPerOneRecord)            
  t.Join(); 
Run Code Online (Sandbox Code Playgroud)

当我将它发送到SOAP Web服务时,除了一个请求之外它工作正常.这些请求彼此混淆.即:

What it should be: 
Record 1 -> SOAP
Record 2 -> SOAP
Record 3 -> SOAP

What it is
Record 1 -> SOAP
Record 2 -> SOAP 
Record 2 -> SOAP 
Record 3 -> nowhere
Run Code Online (Sandbox Code Playgroud)

我已经尝试调试整个代码,并使用调试器工作正常.当我插入50毫秒的睡眠时也一样.但没有睡眠就混合了这两个记录......

有没有人知道为什么会这样?不应该每个线程都独立于自身吗?我还检查了集合,数据正确在里面.

谢谢

Oldfighter

Mag*_*tLU 6

更换

Thread t = new Thread(() => Send(prov, c));
t.Start();
Run Code Online (Sandbox Code Playgroud)

Thread t = new Thread(item => Send(item, c));
t.Start(prov);
Run Code Online (Sandbox Code Playgroud)

在你的代码中,lambda表达式实际上看到了对iterator变量的更改(它是每个线程的相同变量,而不是将lambda传递给线程构造函数时捕获的值).