/// <summary> /// 執行 /// </summary> /// <param name="list">要處理的資料</param> /// <param name="argument">額外的參數</param> public List <PackageWorkEventArgs <T> > Run(IEnumerable <T> list, object argument) { #region 切封包執行 List <PackageWorkEventArgs <T> >[] packages = new List <PackageWorkEventArgs <T> > [_MaxThreads]; for (int i = 0; i < packages.Length; i++) { packages[i] = new List <PackageWorkEventArgs <T> >(); } List <T> package = null; int packagecount = 0; int p = 0; foreach (T var in list) { if (packagecount == 0) { package = new List <T>(_PackageSize); packagecount = _PackageSize; PackageWorkEventArgs <T> pw = new PackageWorkEventArgs <T>(); pw.List = package; pw.Argument = argument; packages[p % _MaxThreads].Add(pw); p++; } package.Add(var); packagecount--; } #region 開多個執行緒跑 List <Thread> otherThreads = new List <Thread>(); for (int i = 1; i < _MaxThreads; i++) { if (packages[i].Count > 0) { Thread backThread = new Thread(new ParameterizedThreadStart(doWork)); backThread.IsBackground = true; backThread.Start(packages[i]); otherThreads.Add(backThread); } } if (packages[0].Count > 0) { doWork(packages[0]); } foreach (Thread thread in otherThreads) { thread.Join(); } #endregion List <PackageWorkEventArgs <T> > result = new List <PackageWorkEventArgs <T> >(); foreach (List <PackageWorkEventArgs <T> > var in packages) { result.AddRange(var); } return(result); #endregion }
private void Worker_PackageWorker(object sender, PackageWorkEventArgs <IN> e) { if (Function == null) { throw new ArgumentException("請指定 RunPart 屬性。"); } List <OUT> result = Function(e.List); lock (Result) { progress += e.List.Count; Result.AddRange(result); } if (ProgressChange != null) { ProgressChange(progress); } }