为什么AutoResetEvent变量不能传递给线程?
实现多线程同时向多个目标地点发送一个文件。
程序如下
AutoResetEvent[] are = new AutoResetEvent[releasePaths.Count]; int _h = 0; foreach (var item in releasePaths) { Console.WriteLine("In:_h={0}", _h); are[_h] = new AutoResetEvent(false); Thread thread = new Thread(() => item.SendFile("2012-9-11.zip", are[_h])); _h++; thread.Start(); } WaitHandle.WaitAll(are);
public bool SendFile(string from, AutoResetEvent autoRE = null) { try { if (lowPath.StartsWith("ftp://")) { try { FTPclient ftpClient = new FTPclient(lowPath, User, Password); return ftpClient.Upload(from, lowPath); } catch (Exception) { return false; } } else { if (!DstPath.EndsWith("\\")) { DstPath += "\\"; } int times = 0; while (times < 10) { try { File.Copy(from, DstPath + System.IO.Path.GetFileName(from), true); return true; } catch (Exception e) { lock (ReleasePath._LockObj) { Log.WriteLog("Exception: " + e.Message); } Thread.Sleep(300000); } times++; } return false; } } finally { if (autoRE != null) { autoRE.Set(); } } }
Thread thread = new Thread(() => item.SendFile("2012-9-11.zip", are[_h]));
Thread thread = new Thread(() => item.SendFile("2012-9-11.zip", null));
---------------------------------------------
要改的话可以用一个封闭在foreach循环中的局部变量代替_h
int _h1=_h;//......Thread thread = new Thread(() => item.SendFile("2012-9-11.zip", are[_h1]));_h++;