/// <summary> /// Create a AsyncDiskServices with a set of volumes (specified by their /// root directories). /// </summary> /// <remarks> /// Create a AsyncDiskServices with a set of volumes (specified by their /// root directories). /// The AsyncDiskServices uses one ThreadPool per volume to do the async /// disk operations. /// </remarks> /// <param name="volumes">The roots of the file system volumes.</param> public AsyncDiskService(string[] volumes) { /* * This class is a container of multiple thread pools, each for a volume, * so that we can schedule async disk operations easily. * * Examples of async disk operations are deletion of files. * We can move the files to a "TO_BE_DELETED" folder before asychronously * deleting it, to make sure the caller can run it faster. */ // ThreadPool core pool size // ThreadPool maximum pool size // ThreadPool keep-alive time for threads over core pool size threadFactory = new _ThreadFactory_73(this); // Create one ThreadPool per volume for (int v = 0; v < volumes.Length; v++) { ThreadPoolExecutor executor = new ThreadPoolExecutor(CoreThreadsPerVolume, MaximumThreadsPerVolume , ThreadsKeepAliveSeconds, TimeUnit.Seconds, new LinkedBlockingQueue <Runnable>() , threadFactory); // This can reduce the number of running threads executor.AllowCoreThreadTimeOut(true); executors[volumes[v]] = executor; } }
private IScenarioThreadFactory CreateScenarioThreadFactory() { IPrewait prewait = new TimerBasedPrewait(_timer); IScenarioThreadFactory factory = new ThreadFactory(prewait, _errorHandler); return(factory); }
//THIS THREAD RECOGNIZES A FACE IN THE BACKGROUND public override void DoWork(object sender, DoWorkEventArgs e) { Debug.WriteLine("Student Recognition Thread Starting"); Debug.WriteLine("Count = " + faces_to_recognize.Count); if (!paused) { //STOP SHOWING THE PROGRESS INDICATOR DisableSpinningProgressIndicator(); //GET ALL FACES TO BE RECOGNIZED List <Image <Bgr, byte> > .Enumerator enumerator = faces_to_recognize.GetEnumerator(); //LOOP THRU ALL FACES TO RECOGNIZE while (enumerator.MoveNext()) { Debug.WriteLine("Student Recognition Thread running"); face_to_recognize = enumerator.Current; //RECOGNIZE THE FACE RecognizeFace(face_to_recognize); //DISPLAY PROGRESS OF THE RECOGNITION OPERATION DisplayFaceRecognitionProgress(); //GENERATE AN ALARM IF RECOGNITION IS SUCESSFUL GenerateAlarm(); //TURN ON ALERT THREAD ThreadFactory.GetThread(ThreadFactory.STUDENT_ALERT_THREAD).Resume(); } } CleanUp(); }
public override void RunInternal() { Setup(); var subGraph = m_compositeComponentMetadata.ComponentGraph; Action method = () => { using (IExperimentRunner dispatcher = ExperimentRunnerFactory.CreateExperimentRunnerForSubLevelExperiment(m_subLevelExperiment)) { dispatcher.NodeExecuting += subGraph.dispatcher_NodeExecuting; dispatcher.NodeFinished += subGraph.dispatcher_NodeFinished; dispatcher.NodeHasError += subGraph.dispatcher_NodeHasError; dispatcher.ExperimentFinished += (s, a) => { dispatcher.NodeExecuting -= subGraph.dispatcher_NodeExecuting; dispatcher.NodeFinished -= subGraph.dispatcher_NodeFinished; dispatcher.NodeHasError -= subGraph.dispatcher_NodeHasError; }; dispatcher.ExecuteExperiment(null); } }; Thread dispatchThread = ThreadFactory.CreateThread(new System.Threading.ThreadStart(method)); dispatchThread.IsBackground = true; dispatchThread.Name = "SubExperimentRunner"; dispatchThread.SetApartmentState(System.Threading.ApartmentState.STA); dispatchThread.Start(); dispatchThread.Join(); TearDown(); }
public void StartNew_Multiple() { const int threadCount = 32; var nums = new ConcurrentBag <int>(); var threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = ThreadFactory.StartNew(i, nums.Add); } for (int i = 0; i < threadCount; i++) { threads[i].Join(); } EnumerableAssert.AreEquivalent(Enumerable.Range(0, threadCount), nums); nums = new ConcurrentBag <int>(); Enumerable.Range(0, threadCount) .Select(i => ThreadFactory.StartNew(() => nums.Add(i))) .ToList() .ForEach(thread => thread.Join()); EnumerableAssert.AreEquivalent(Enumerable.Range(0, threadCount), nums); }
private volatile ThreadTask _task; // Current task public ThreadWorker(ThreadFactory parent, string name = null) { Name = name; _factory = parent; _thread = new Thread(_Work); _thread.Start(); }
public DirectImportOperation(ThumbnailRenderer thumbnailRenderer, ThreadFactory threadFactory) { this.thumbnailRenderer = thumbnailRenderer; this.threadFactory = threadFactory; AllowCancel = true; }
/// <summary> /// Runs the experiement. /// </summary> /// <param name="progress">The progress.</param> /// <param name="experiment">The experiment.</param> /// <param name="baseline">(optional) The baseline data that is going to be preloaded into workspace before executing the experiment.</param> public void RunExperiment(IProgress progress, Workspace workspace, ComponentsLibrary library, TraceLabSDK.Types.Contests.TLExperimentResults baseline) { progress.CurrentStatus = "Preparing experiment..."; progress.IsIndeterminate = true; progress.SetError(false); ClearErrors(); Action method = () => { //prevent the component library from rescanning while running the experiment using (var rescanLibraryGuard = new RescanLibraryGuard(library)) { using (var dispatcher = CreateExperimentRunner(workspace, library, baseline)) { dispatcher.ExecuteExperiment(progress); } } }; Thread dispatchThread = ThreadFactory.CreateThread(new System.Threading.ThreadStart(method)); dispatchThread.IsBackground = true; dispatchThread.Name = "ExperimentRunner"; dispatchThread.SetApartmentState(System.Threading.ApartmentState.STA); dispatchThread.Start(); }
public WiaScanDriver(IWiaTransfer wiaTransfer, ThreadFactory threadFactory, IBlankDetector blankDetector, ThumbnailRenderer thumbnailRenderer) { this.wiaTransfer = wiaTransfer; this.threadFactory = threadFactory; this.blankDetector = blankDetector; this.thumbnailRenderer = thumbnailRenderer; }
/// <summary> /// Detects process analysers, such as sandboxes, virtual environments, or specific debuggers or profilers. /// </summary> /// <param name="processAnalyser">The <see cref="ProcessAnalyser" /> to test.</param> /// <returns> /// <see langword="true" />, if the specified process analyser has been detected; /// otherwise, <see langword="false" />. /// </returns> public static bool DetectProcessAnalyser(ProcessAnalyser processAnalyser) { //FEATURE: Sandboxes, virtual machines, CheatEngine (https://www.aspfree.com/c/a/braindump/virtualization-and-sandbox-detection/) if (processAnalyser == ProcessAnalyser.Sandboxie) { return(Native.GetModuleHandle("SbieDll") != IntPtr.Zero); } else if (processAnalyser == ProcessAnalyser.Emulator) { int start = Environment.TickCount; Stopwatch stopwatch = ThreadFactory.StartStopwatch(); Thread.Sleep(500); int stop = Environment.TickCount; return(stop - start < 450 || stopwatch.Elapsed < TimeSpan.FromMilliseconds(450)); } else if (processAnalyser == ProcessAnalyser.Wireshark) { return(Process.GetProcessesByName("Wireshark").Any() || Process.GetProcesses().Any(process => CSharp.Try(() => process?.MainWindowTitle).Equals("The Wireshark Network Analyzer", SpecialStringComparisons.NullAndEmptyEqual | SpecialStringComparisons.IgnoreCase))); } else if (processAnalyser == ProcessAnalyser.ProcessMonitor) { return(Process.GetProcesses().Any(process => CSharp.Try(() => process?.MainWindowTitle).Contains("Process Monitor -", SpecialStringComparisons.IgnoreCase))); } else { throw Throw.InvalidEnumArgument(nameof(processAnalyser), processAnalyser); } }
/// <summary> /// Initializes a new instance of the <see cref="GroveBarDevice"/> class. /// </summary> /// <param name="dataPin">The data pin.</param> /// <param name="clockPin">The clock pin.</param> /// <param name="threadFactory">The thread factory.</param> public GroveBarDevice(IOutputBinaryPin dataPin, IInputOutputBinaryPin clockPin, IThreadFactory threadFactory = null) { this.dataPin = dataPin; this.clockPin = clockPin; this.thread = ThreadFactory.EnsureThreadFactory(threadFactory).Create(); this.Initialize(); }
/// <summary> /// Executes a .NET executable from a <see cref="byte" />[] by invoking the main entry point. The Main method must either have no parameters or one <see cref="string" />[] parameter. If it has a parameter, <paramref name="args" /> is passed, otherwise <paramref name="args" /> is ignored. /// </summary> /// <param name="executable">A <see cref="byte" />[] that represents a .NET executable file.</param> /// <param name="args">A <see cref="string" />[] representing the arguments that is passed to the main entry point, if the Main method has a <see cref="string" />[] parameter.</param> /// <param name="thread"><see langword="true" /> to invoke the main entry point in a new thread.</param> public static void ExecuteDotNetAssembly(byte[] executable, string[] args, bool thread) { Check.ArgumentNull(executable, nameof(executable)); MethodInfo method = Assembly.Load(executable).EntryPoint; ParameterInfo[] parameters = method.GetParameters(); Action invoke; if (parameters.Length == 0) { invoke = () => method.Invoke(); } else if (parameters.Length == 1 && parameters.First().ParameterType == typeof(string[])) { invoke = () => method.Invoke(null, new[] { args ?? new string[0] }); } else { throw Throw.InvalidOperation("Executable does not contain a static 'main' method suitable for an entry point."); } if (thread) { ThreadFactory.StartThread(invoke); } else { invoke(); } }
public DeskewOperation(ThreadFactory threadFactory, ThumbnailRenderer thumbnailRenderer) { this.threadFactory = threadFactory; this.thumbnailRenderer = thumbnailRenderer; AllowCancel = true; }
private void button_camera_enroll_Click(object sender, EventArgs e) { button_camera_enroll.Enabled = false; ThreadFactory.StopReviewFootageThreads(); Singleton.ClearReviewFootageDataStores(); ThreadFactory.ReleaseAllThreadResources(); //WHEN THIS BUTTON IS CLICKED //A CONFIRMATION MESSAGE BOX POPS UP //ON CONFIRMATION A CHECK IS MADE TO ENSURE THAT THE SYSTEM HAS ATLEAST A CAMERA CONNECTED //NECESSARY THREADS ARE SPAWNED //AND THE FRAMES ARE GRABBED FROM THE CONNECTED CAMERA PickCameraForm form = new PickCameraForm(); DisableReviewControls(); form.ShowDialog(); if (form.selected_camera != null) { ThreadFactory.StartReviewFootageThreadsUsingCamera(form.selected_camera); Debug.WriteLine("Enabling review controls 1"); EnableReviewControls(); Debug.WriteLine("Enabling review controls 2"); } Debug.WriteLine("Enabling review controls 3"); EnableReviewControls(); }
/// <summary> /// Runs creates the thread with specified specified arguments and starts this thread. /// </summary> /// <param name="args">The args.</param> /// <returns>The the AutoResetEvent that will signal, when the thread finishes.</returns> public AutoResetEvent Run(RunnableNodeThreadArgs args) { if (args == null || args.ExperimentRunner == null) { throw new ArgumentNullException("args", "RunnableNodeThreadArgs and its dispatcher cannot be null to start a thread"); } args.Node = this; // Sets the state of the reset event to nonsignaled m_nodeResetEvent.Reset(); // Create a task and supply a user delegate by using a lambda expression. var nodeThread = ThreadFactory.CreateThread(new ParameterizedThreadStart(ThreadRun)); nodeThread.Name = String.Format("Worker: {0}, {1}", Id, Label); nodeThread.IsBackground = true; nodeThread.SetApartmentState(ApartmentState.STA); nodeThread.Start(args); m_nodeThread = nodeThread; return(m_nodeResetEvent); }
/// <summary> /// Initializes a new instance of the <see cref="ProcessSharp" /> class. /// </summary> /// <param name="native">The native process.</param> /// <param name="type">The type of memory being manipulated.</param> public ProcessSharp(Process native, MemoryType type) { native.EnableRaisingEvents = true; native.Exited += (s, e) => { ProcessExited?.Invoke(s, e); HandleProcessExiting(); }; Native = native; Handle = MemoryHelper.OpenProcess(ProcessAccessFlags.AllAccess, Native.Id); switch (type) { case MemoryType.Local: Memory = new LocalProcessMemory(Handle); break; case MemoryType.Remote: Memory = new ExternalProcessMemory(Handle); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } native.ErrorDataReceived += OutputDataReceived; native.OutputDataReceived += OutputDataReceived; ThreadFactory = new ThreadFactory(this); ModuleFactory = new ModuleFactory(this); MemoryFactory = new MemoryFactory(this); WindowFactory = new WindowFactory(this); }
/// <param name="tf"> used to create IO threads to listen and handle network events </param> /// <param name="initializersMap"> function per bolt connector map to bootstrap configured protocols </param> /// <param name="connectorRegister"> register to keep local address information on all configured connectors </param> public NettyServer(ThreadFactory tf, IDictionary <BoltConnector, ProtocolInitializer> initializersMap, ConnectorPortRegister connectorRegister, Log log) { this._bootstrappersMap = initializersMap; this._tf = tf; this._connectionRegister = connectorRegister; this._log = log; }
private static ExecutorService BuildExecutorService(JobScheduler scheduler) { BlockingQueue <ThreadStart> workQueue = new LinkedBlockingQueue <ThreadStart>(_ioParallelism * 4); RejectedExecutionHandler rejectionPolicy = new ThreadPoolExecutor.CallerRunsPolicy(); ThreadFactory threadFactory = scheduler.ThreadFactory(Group.FILE_IO_HELPER); return(new ThreadPoolExecutor(0, _ioParallelism, 10, TimeUnit.SECONDS, workQueue, threadFactory, rejectionPolicy)); }
public WiaScanDriver(BackgroundWiaTransfer backgroundWiaTransfer, ForegroundWiaTransfer foregroundWiaTransfer, ThreadFactory threadFactory, IBlankDetector blankDetector, ThumbnailRenderer thumbnailRenderer) { this.backgroundWiaTransfer = backgroundWiaTransfer; this.foregroundWiaTransfer = foregroundWiaTransfer; this.threadFactory = threadFactory; this.blankDetector = blankDetector; this.thumbnailRenderer = thumbnailRenderer; }
public ImportOperation(IScannedImageImporter scannedImageImporter, ThreadFactory threadFactory) { this.scannedImageImporter = scannedImageImporter; this.threadFactory = threadFactory; ProgressTitle = MiscResources.ImportProgress; AllowCancel = true; }
private List <Thread> ThreadRange( int numThreads, ThreadFactory threadFactory) { return(Enumerable.Range(0, numThreads) .Select(_ => threadFactory.Invoke(Run)) .ToList()); }
/// <summary> /// Initializes a new instance of the <see cref="Pca9685Device" /> class. /// </summary> /// <param name="connection">The I2C connection.</param> /// <param name="threadFactory">The thread factory.</param> /// <param name="pca9685DeviceReporter">The pca9685 device reporter.</param> public Pca9685Device(I2cDeviceConnection connection, IThreadFactory threadFactory = null, IPca9685DeviceReporter pca9685DeviceReporter = null) { this.connection = connection; this.pca9685DeviceReporter = pca9685DeviceReporter; this.thread = ThreadFactory.EnsureThreadFactory(threadFactory).Create(); this.pca9685DeviceReporter?.Resetting(); this.WriteRegister(Register.Mode1, 0x00); }
private ExecutorService CreateThreadPool() { int threads = NumberOfPopulationWorkers; BlockingQueue <ThreadStart> workQueue = new LinkedBlockingQueue <ThreadStart>(_taskQueueSize); ThreadFactory threadFactory = daemon(FLUSH_THREAD_NAME_PREFIX); RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); return(new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, workQueue, threadFactory, rejectedExecutionHandler)); }
public override Thread NewThread(ThreadStart runnable) { ThreadFactory factory = Executors.defaultThreadFactory(); Thread thread = factory.newThread(runnable); thread.Daemon = true; thread.Name = _prefix + _counter.AndIncrement; return(thread); }
static Device() { Thread = ThreadFactory.Create(); Network = NetworkFactory.Create(); DataPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); //Session = new SerializableDictionary<string, object>(); //Settings = new SerializableDictionary<string, string>(); }
public RecoveryOperation(IFormFactory formFactory, ThreadFactory threadFactory, ThumbnailRenderer thumbnailRenderer) { this.formFactory = formFactory; this.threadFactory = threadFactory; this.thumbnailRenderer = thumbnailRenderer; ProgressTitle = MiscResources.ImportProgress; AllowCancel = true; }
public MessageHandler( IMessageReceiver protocol, Action <IMessage> messageHandlerDelegate, ThreadFactory threadFactory) { this.protocol = protocol; this.messageHandlerDelegate = messageHandlerDelegate; this.handlingThread = threadFactory.CreateThread(new ThreadStart(ReceiverLoop)); }
public ThreadPerTaskExecutor(ThreadFactory threadFactory) { if (threadFactory == null) { throw new NullReferenceException("threadFactory"); } this.threadFactory = threadFactory; }
public BuildProgressDialogViewModel(BuildProgressDialog view, string outputFileName, Process process) { View = view; OutputFileName = outputFileName; Process = process; Process.Start(); Timer = ThreadFactory.StartDispatcherTimer(Timer_Tick, TimeSpan.FromMilliseconds(10)); }
public SavePdfOperation(FileNamePlaceholders fileNamePlaceholders, IPdfExporter pdfExporter, IOverwritePrompt overwritePrompt, ThreadFactory threadFactory) { this.fileNamePlaceholders = fileNamePlaceholders; this.pdfExporter = pdfExporter; this.overwritePrompt = overwritePrompt; this.threadFactory = threadFactory; AllowCancel = true; }
public AsynchronousChannelGroup openAsynchronousChannelGroup(int arg0, ThreadFactory arg1) { return Instance.CallMethod<AsynchronousChannelGroup>("openAsynchronousChannelGroup", "(ILjava/util/concurrent/ThreadFactory;)Ljava/nio/channels/AsynchronousChannelGroup;", arg0, arg1); }
public void setThreadFactory(ThreadFactory arg0) { Instance.CallMethod("setThreadFactory", "(Ljava/util/concurrent/ThreadFactory;)V", arg0); }
public ThreadPoolExecutor(int arg0, int arg1, long arg2, TimeUnit arg3, BlockingQueue<Runnable> arg4, ThreadFactory arg5) : base(ProxyCtor.I) { Instance.CallConstructor("(IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V", arg0, arg1, arg2, arg3, arg4, arg5); }
public static AsynchronousChannelGroup withFixedThreadPool(int arg0, ThreadFactory arg1) { return Static.CallMethod<AsynchronousChannelGroup>(typeof(AsynchronousChannelGroup), "withFixedThreadPool", "(ILjava/util/concurrent/ThreadFactory;)Ljava/nio/channels/AsynchronousChannelGroup;", arg0, arg1); }