/// <summary> /// 被动监测目前局域网内的所有设备(导致阻塞)。 /// </summary> /// <exception cref="TimeoutException">等待分析线程终止超时。</exception> public void SpyForTarget() { // 获取当前设备 var device = DeviceList[CurDevName]; // 创建分析线程 var analyzeThreads = new Thread[8]; try { // 开始扫描 device = StartCapture("arp"); // 初始化分析线程 for (var i = 0; i < 8; i++) { analyzeThreads[i] = new Thread(ScanPacketAnalyzeThread); analyzeThreads[i].Start(); } // 如果分析线程异常终止,则结束监听 while (analyzeThreads.All(analyzeThread => analyzeThread.IsAlive)) { Thread.Sleep(800); } } catch (ThreadAbortException) { // 终止分析线程 foreach (var analyzeThread in analyzeThreads) { analyzeThread.Abort(); } } finally { // 终止分析线程 foreach (var analyzeThread in analyzeThreads) { if (analyzeThread.IsAlive) { analyzeThread.Abort(); } } // 等待分析线程终止 new WaitTimeoutChecker(30000).ThreadSleep(500, () => analyzeThreads.Any(analyzeThread => analyzeThread.IsAlive)); // 清理缓冲区及其他内容 lock (_hostList) { _hostList.Sort(Host.SortMethod); } StopCapture(device); ClearCaptures(); } }
public IEnumerator NewTestScriptWithEnumeratorPasses() { Thread[] t = new Thread[1]; for (int i = 0; i < t.Length; ++i) { t[i] = new Thread(ThreadProc); t[i].Start(new ProtobufSerializer2()); } //ThreadProc(); //Assert.Pass(); while (true) { if (t.All(thread => !thread.IsAlive)) { Assert.Pass(); break; } yield return(null); } }
}//Метод при помощи которого мы получаем файлы изображения из папки. static void Main(string[] args) { path = @"C:\Users\FORzzMOK\Desktop\Pavel"; turnAngel = RotateFlipType.Rotate90FlipNone; ImageFiles = GetImageFiles(path); int ThreadCount = Environment.ProcessorCount; if (ImageFiles != null) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread[] myThread = new Thread[ThreadCount]; for (int i = 0; i < ThreadCount; i++) { myThread[i] = new Thread(ImageTurn); myThread[i].Start(); } while (true) { if (myThread.All(T => !T.IsAlive)) { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); break; } Thread.Sleep(500); } } Console.WriteLine("End... "); Console.ReadLine(); }
public async Task TestConcurrentReadWriteAsync() { var l = new AsyncReaderWriterLock(); for (var i = 0; i < 2; i++) { var writeReleaser = await(l.WriteLockAsync()); Assert.That(l.Writing, Is.True); var secondWriteSemaphore = new SemaphoreSlim(0); var secondWriteReleaser = default(AsyncReaderWriterLock.Releaser); var secondWriteThread = new Thread( () => { secondWriteSemaphore.Wait(); secondWriteReleaser = l.WriteLock(); }); secondWriteThread.Priority = ThreadPriority.Highest; secondWriteThread.Start(); await(AssertEqualValueAsync(() => secondWriteThread.ThreadState == ThreadState.WaitSleepJoin, true)); var secondReadThreads = new Thread[20]; var secondReadReleasers = new AsyncReaderWriterLock.Releaser[secondReadThreads.Length]; var secondReadSemaphore = new SemaphoreSlim(0); for (var j = 0; j < secondReadReleasers.Length; j++) { var index = j; var thread = new Thread( () => { secondReadSemaphore.Wait(); secondReadReleasers[index] = l.ReadLock(); }); thread.Priority = ThreadPriority.Highest; secondReadThreads[j] = thread; thread.Start(); } await(AssertEqualValueAsync(() => secondReadThreads.All(o => o.ThreadState == ThreadState.WaitSleepJoin), true)); var firstReadReleaserTasks = new Task[30]; var firstReadStopSemaphore = new SemaphoreSlim(0); for (var j = 0; j < firstReadReleaserTasks.Length; j++) { firstReadReleaserTasks[j] = Task.Run(async() => { var releaser = await(l.ReadLockAsync()); await(firstReadStopSemaphore.WaitAsync()); releaser.Dispose(); }); } await(AssertEqualValueAsync(() => l.ReadersWaiting, firstReadReleaserTasks.Length, waitDelay: 60000)); writeReleaser.Dispose(); secondWriteSemaphore.Release(); secondReadSemaphore.Release(secondReadThreads.Length); await(Task.Delay(1000)); firstReadStopSemaphore.Release(firstReadReleaserTasks.Length); await(AssertEqualValueAsync(() => firstReadReleaserTasks.All(o => o.IsCompleted), true)); Assert.That(l.ReadersWaiting, Is.EqualTo(secondReadThreads.Length)); Assert.That(l.CurrentReaders, Is.EqualTo(0)); await(AssertEqualValueAsync(() => secondWriteThread.IsAlive, false)); await(AssertEqualValueAsync(() => secondReadThreads.All(o => o.IsAlive), true)); secondWriteReleaser.Dispose(); await(AssertEqualValueAsync(() => secondReadThreads.All(o => !o.IsAlive), true)); Assert.That(l.ReadersWaiting, Is.EqualTo(0)); Assert.That(l.CurrentReaders, Is.EqualTo(secondReadThreads.Length)); foreach (var secondReadReleaser in secondReadReleasers) { secondReadReleaser.Dispose(); } Assert.That(l.ReadersWaiting, Is.EqualTo(0)); Assert.That(l.CurrentReaders, Is.EqualTo(0)); } }
public IEnumerable <updateFile> getFilesForImage(string absoluteFilename, int imageIndex) { string mountpoint = null; string convertedPath = null; // If the mountpoint already has something mounted in it, umount it first. mountpoint = Path.Combine(Program.tempdir, $"mountpoint_{Path.GetFileName(parent.filename)}_{imageIndex}"); string wiminfostdout = wsusUpdate.runAndGetStdout("dism", "/get-mountedwiminfo"); string[] activemountpoints = wiminfostdout.Split('\n') .Where(x => x.StartsWith("Mount Dir :")) .Select(x => x.Substring("Mount Dir :".Length).Trim()) .ToArray(); if (activemountpoints.Count(x => x == mountpoint) > 0) { wsusUpdate.runAndGetStdout("dism", $"/unmount-wim /mountdir:{mountpoint} /discard"); } deleteWithRetry(mountpoint); Directory.CreateDirectory(mountpoint); try { // Before we can mount an .esd, we must convert it to a .wim. convertedPath = Path.Combine(Program.tempdir, Path.GetFileName(parent.filename) + "_" + imageIndex + ".wim"); deleteWithRetry(convertedPath); wsusUpdate.runAndGetStdout("dism", $"/export-image /quiet /sourceimagefile:{absoluteFilename} " + $"/sourceindex:{imageIndex} /DestinationImageFile:{convertedPath} /Compress:Max /CheckIntegrity"); // Mount the image and examine the files within. ConcurrentQueue <queuedFileCreation> createQueue = new ConcurrentQueue <queuedFileCreation>(); ConcurrentQueue <updateFile> output = new ConcurrentQueue <updateFile>(); ConcurrentQueue <Tuple <Exception, string> > errors = new ConcurrentQueue <Tuple <Exception, string> >(); using (mountedDISMImage img = new mountedDISMImage(convertedPath, 1, mountpoint)) { AutoResetEvent newInfoQueued = new AutoResetEvent(false); AutoResetEvent newFileCreated = new AutoResetEvent(false); bool exitThreads = false; int threadCount = Environment.ProcessorCount; Thread[] hashingThreads = new Thread[threadCount]; for (int n = 0; n < threadCount; n++) { hashingThreads[n] = new Thread((() => { while (true) { if (createQueue.IsEmpty) { if (exitThreads) { if (createQueue.IsEmpty) { break; } } } if (createQueue.TryDequeue(out queuedFileCreation toCreate) == false) { newInfoQueued.WaitOne(10); continue; } try { output.Enqueue(new updateFile(toCreate.file, toCreate.relativePath)); newFileCreated.Set(); } catch (UnauthorizedAccessException) { // Some files will throw this. :( if (toCreate.relativePath.Contains("MpScanCache-0.bin") || toCreate.relativePath.Contains("RtBackup")) { continue; } errors.Enqueue(new Tuple <Exception, string>(null, $"Unable to access file {toCreate.relativePath}, saw an UnauthorizedAccessException")); continue; } catch (Exception e) { // Should never happen but probably will. errors.Enqueue(new Tuple <Exception, string>(e, $"Unable to access file {toCreate.relativePath}")); continue; } } })); hashingThreads[n].Name = $"File examining thread {n}"; hashingThreads[n].Start(); } IEnumerable <updateFile> files = enumFilesOnDisk <updateFile>(mountpoint, delegate(string file, string relativePath) { createQueue.Enqueue(new queuedFileCreation(file, relativePath)); newInfoQueued.Set(); return(null); }); foreach (updateFile updateFile in files) { // ... } exitThreads = true; while (true) { if (createQueue.IsEmpty) { if (output.IsEmpty && errors.IsEmpty) { if (hashingThreads.All(x => x.IsAlive == false)) { break; } } } if (errors.IsEmpty == false && errors.TryDequeue(out var error)) { if (error.Item1 == null) { logString(error.Item2); } else { logString(error.Item1, error.Item2); } } if (output.IsEmpty == true || output.TryDequeue(out updateFile outputFile) == false) { newFileCreated.WaitOne(10); continue; } yield return(outputFile); } /* * IEnumerable<updateFile> files = enumFilesOnDisk<updateFile>(mountpoint, * delegate (string file, string relativePath) * { * return new updateFile(file, relativePath); * }); * foreach (updateFile updateFile in files) * yield return updateFile;*/ } } finally { deleteWithRetry(mountpoint); deleteWithRetry(convertedPath); } }