/// <summary> /// 开始搜索数据 /// </summary> /// <param name="files"></param> /// <param name="searchData"></param> private void StartSearch(FileInfo[] files, byte[] searchData) { var next = Preprocess.Next(searchData); for (int i = 0; i < processorCount; i++) { WorkerParameter param = new WorkerParameter { StartIndex = i, Files = files, SearchData = searchData, Next = next }; ParameterizedThreadStart pts = Worker; new Thread(pts).Start(param); } }
/// <summary> /// 工作线程 /// </summary> /// <param name="startIndex"></param> /// <param name="files"></param> /// <param name="searchData"></param> private void Worker(object param) { WorkerParameter wp = (WorkerParameter)param; for (int i = wp.StartIndex; i < wp.Files.Length; i += processorCount) { FileDataSearch searcher = new FileDataSearch(); long[] foundIndices = searcher.KMPSearch(wp.Files[i], wp.SearchData, wp.Next); //long[] foundIndices = searcher.SearchFor(wp.Files[i], wp.SearchData); if (foundIndices.Length > 0) { foreach (var index in foundIndices) { FileResult result = new FileResult { Display = string.Format("{0}(偏移: 0x{1:X})", wp.Files[i].Name, index), FullPath = wp.Files[i].FullName }; BeginInvoke(new Action(() => lbResult.Items.Add(result))); Interlocked.Increment(ref totalFound); } } } Interlocked.Increment(ref completeCount); //判断是否所有线程都工作完毕 if (completeCount == processorCount) { BeginInvoke(new Action(() => { watch.Stop(); statusText.Text = string.Format("搜索完毕,在{0}个文件中共找到匹配文件:{1}个(耗时:{2}ms)", wp.Files.Length, totalFound, watch.ElapsedMilliseconds); watch.Reset(); totalFound = 0; })); completeCount = 0; } }