/// <summary> /// Do our best to kill a thread, passing state info /// </summary> /// <param name="thread">The thread to kill</param> /// <param name="stateInfo">Info for the ThreadAbortException handler</param> public static void Kill(Thread thread, object stateInfo) { try { if (stateInfo == null) thread.Abort(); else thread.Abort(stateInfo); } catch (ThreadStateException) { #if !NETCF // Although obsolete, this use of Resume() takes care of // the odd case where a ThreadStateException is received. #pragma warning disable 0618,0612 // Thread.Resume has been deprecated thread.Resume(); #pragma warning restore 0618,0612 // Thread.Resume has been deprecated #endif } #if !NETCF if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 ) thread.Interrupt(); #endif }
static void RunWithTimeout(Action entryPoint, int timeout) { Thread thread = null; try { thread = new Thread(() => entryPoint()) { IsBackground = true }; if (thread != null) { thread.Start(); if(thread.IsAlive) thread.Join(timeout); } } catch (Exception ex) { ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, null, "ошибка запуска задания " + ex.Message,-1); } finally { if (thread != null) thread.Abort(); if (thread != null) thread.Join(3000); if (thread != null) thread.Interrupt(); if (thread != null) GC.SuppressFinalize(thread); }; thread = null; }
private static string ReceiveCommandsFromPipe(string pipeName, uint timeout) { string result = null; Thread thread = new System.Threading.Thread(() => { result = ReadFromPipe(pipeName); }); thread.Start(); if (timeout == 0) { Info($"[.] Will wait infinitely long for data to read from pipe."); thread.Join(); } else { Info($"[.] Will wait {timeout} milliseconds for data to read from pipe."); thread.Join((int)timeout); } thread.Interrupt(); if (result != null) { Info($"[.] Read from pipe ({result.Length} bytes)."); return(result); } return(""); }
private void ClientControl_Disposed(object sender, EventArgs e) { isExiting = true; if (assignedMap != null) { assignedMap.Dispose(); } if (receivedMap != null) { receivedMap.Dispose(); } if (fog != null) { fog.Dispose(); } if (connection != null) { connection.Stop(); } if (gridPen != null) { gridPen.Dispose(); } if (zoomFactorHandlerThread != null && zoomFactorHandlerThread.IsAlive) { zoomFactorHandlerThread.Interrupt(); } if (zoomFactorHandlerEvent != null) { zoomFactorHandlerEvent.Set(); zoomFactorHandlerEvent.Dispose(); zoomFactorHandlerEvent = null; } }
public void ConnectTo_GivenTheOutletHasASender_ThrowsAnInvalidOperationException() { // Arrange var pipe2 = PipeBuilder.New.BasicPipe<int>().Build(); var thread = new Thread(() => { try { simpleOutlet.Receive(); } catch { // ignored } }); thread.Start(); Thread.Sleep(500); // Act try { simpleOutlet.ConnectTo(pipe2.Inlet); } catch { thread.Interrupt(); throw; } }
public void SimpleTest() { var goodThread = new Thread(() => { Console.WriteLine("Good"); Assert.IsFalse(Thread.CurrentThread.IsThreadPoolThread); Assert.IsFalse(Thread.CurrentThread.IsBackground); Assert.IsTrue(Thread.CurrentThread.IsAlive); Assert.IsTrue(Thread.CurrentThread.ApartmentState == ApartmentState.MTA); Assert.IsTrue(Thread.CurrentThread.Priority == ThreadPriority.Normal); Assert.IsTrue(Thread.CurrentThread.ThreadState == ThreadState.Running); ThreadInterruptedException Exception = null; try { Thread.Sleep(5000); } catch (ThreadInterruptedException ex) { Exception = ex; } Assert.IsNotNull(Exception); }); goodThread.Start(); Thread.Sleep(50); goodThread.Interrupt(); }
public override void Execute(IList<string> parameters) { dev = GetDevice (parameters); Console.Write ("Connecting: ."); var connection = new Thread (SetupDaemon); connecting = true; connection.Start (); try { var chars = "\\|/-"; var i = 0; Console.CursorVisible = false; while (connecting) { Thread.Sleep (100); Console.SetCursorPosition (Console.CursorLeft - 1, Console.CursorTop); Console.Write (chars [i++ % chars.Length]); } } finally { Console.WriteLine (); Console.CursorVisible = true; } if (errors.Count == 0) { Run (String.Format ("ssh -i {0} devuser@{1}", Application.Configuration.SSHPrivateKey, dev.IP)); connection.Interrupt (); } else { foreach (var i in errors) { Console.Error.WriteLine (i); } } connection.Join (); }
public void TestThrowExceptionAtInsert() { IPoller p = PollerFactory.GetPoller(@".\..\..\shared", @".\..\..\tmp", 10, "testTitle", "Alex Gyori"); using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()) { int i = 0; PdfConversion.Server.Converter.Fakes.ShimImageToPdfConverter.AllInstances.ConvertString = (a, f) => { i++; return true; }; System.IO.Fakes.ShimDirectory.GetFilesString = str => new String[5] { "a", "b", "c", "d", "e" }; System.IO.Fakes.ShimFile.MoveStringString = (a, b) => { }; PdfConversion.Server.DataService.Fakes.ShimFileStatusRepositoryFactory.GetRepository = () => { var repoStub = new PdfConversion.Server.DataService.Fakes.StubIRepository<FileStatusEntity>(); repoStub.InsertT0 = ent => { throw new Exception(); }; repoStub.SaveChanges = () => { }; return repoStub; }; Thread pollingThread = new Thread(p.Poll); pollingThread.Start(); Thread.Sleep(2000); pollingThread.Interrupt(); Assert.IsTrue(i == 0); } }
public void Interrupt_thread_does_not_throw_if_not_blocked() { bool threadInterrupted = false; var t = new Thread(() => { try { for (int i = 0; i < 1000; i++) { Console.Write(i); } } catch (ThreadInterruptedException e) { threadInterrupted = true; Console.Write("Forcibly ..."); } Console.WriteLine("Woken!"); }); t.Start(); t.Interrupt(); t.Join(); Assert.That(threadInterrupted, Is.False); }
public void RedirectionFinalizationTest() { object synchro = new object(); bool done = false; ErrorRedirection test = new ErrorRedirection(); test = null; Thread thread = new Thread(() => { GC.Collect(); GC.WaitForPendingFinalizers(); lock (synchro) { done = true; Monitor.Pulse(synchro); } }); thread.Start(); lock (synchro) { if (!done) { Monitor.Wait(synchro, 1000); } } thread.Interrupt(); }
/// <summary> /// Return a list of file locks held by the process. /// </summary> public static List<string> GetFilesLockedBy(Process process) { var outp = new List<string>(); ThreadStart ts = delegate { try { outp = UnsafeGetFilesLockedBy(process); } catch { Ignore(); } }; try { var t = new Thread(ts); t.IsBackground = true; t.Start(); if (!t.Join(250)) { try { t.Interrupt(); t.Abort(); } catch { Ignore(); } } } catch { Ignore(); } return outp; }
public void Run() { int timeout = 1000; StayAwake sa = new StayAwake(); Thread monitorThread = new Thread(new ThreadStart( () => { // create actual work thread. Thread actualWorkThread = new Thread(new ThreadStart(sa.ThreadMethod)); actualWorkThread.Name = "actual worker"; actualWorkThread.Start(); try { Console.WriteLine("{0} start to sleep. {1}", Thread.CurrentThread.Name, DateTime.Now); Thread.Sleep(timeout); // monitor thread sleep 10s. Console.WriteLine("{0} wake up, and will interrupt worker. {1}", Thread.CurrentThread.Name, DateTime.Now); actualWorkThread.Interrupt(); } catch (ThreadInterruptedException e) { Console.WriteLine(">>> {0} is interrupted.", Thread.CurrentThread.Name); } })); monitorThread.Name = "Monitor"; monitorThread.Start(); sa.SleepSwitch = true; }
static void Main(string[] args) { mServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { IPAddress HostIp = IPAddress.Any; IPEndPoint iep = new IPEndPoint(HostIp, 2626); BlinkLog.I("Start Server Socket..."); mServer.Bind(iep); mServer.Listen(Int32.MaxValue); mThread = new Thread(Run); mThread.Start(); } catch (Exception) { BlinkLog.E("Start Server Error."); } BlinkLog.I("=========PRESS ANY KEY TO EXIT=========="); Console.ReadKey(); IsExit = true; if (mThread != null) { mThread.Interrupt(); } mServer.Dispose(); mServer.Close(); }
private static void MenuComandos(Thread thread) { MenuOpcao(); do { _arquivos = Directory.GetFiles(_origem).ToList(); switch (_opcao) { case "start": Thread.Sleep(3000); thread.Start(); MenuComandos(thread = new Thread(MoveFile)); break; case "pause": Thread.Sleep(3000); thread.Interrupt(); MenuComandos(thread = new Thread(MoveFile)); break; case "resume": Thread.Sleep(3000); thread.Resume(); MenuComandos(thread = new Thread(MoveFile)); break; case "abort": Thread.Sleep(3000); thread.Abort(); MenuComandos(thread = new Thread(MoveFile)); break; default: Console.WriteLine("Comando incorreto"); break; } } while (_arquivos.Count > 0); }
public void TestNoTimeoutConsumer( [Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode) { // Launch a thread to perform IMessageConsumer.Receive(). // If it doesn't fail in less than three seconds, no exception was thrown. Thread receiveThread = new Thread(new ThreadStart(TimeoutConsumerThreadProc)); using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(ackMode)) { ITemporaryQueue queue = session.CreateTemporaryQueue(); using(this.timeoutConsumer = session.CreateConsumer(queue)) { receiveThread.Start(); if(receiveThread.Join(3000)) { Assert.Fail("IMessageConsumer.Receive() returned without blocking. Test failed."); } else { // Kill the thread - otherwise it'll sit in Receive() until a message arrives. receiveThread.Interrupt(); } } } } }
/** * Terminates the component. * * @param newStatus the new status of the component (mostly TERMINATED or ERROR) */ internal virtual void Terminate(States newStatus) { _status = newStatus; if (_thread != null) { _thread.Interrupt(); } }
/// <summary> /// Interrupts a SThread that is in the WaitSleepJoin SThread state /// </summary> public virtual void Interrupt() { if (exitedPool("Interupt")) { return; } threadField.Interrupt(); }
public void interrupt() { try { t.Interrupt(); } catch { } }
public void TimedExchange_InterruptedException() { Exchanger e = new Exchanger(); Thread t = new Thread(new AnonymousClassRunnable5(e).Run); t.Start(); t.Interrupt(); t.Join(); }
public static void Main(string[] args) { pingUDP pingClass = new pingUDP(); Thread trd = new Thread( new ThreadStart(pingClass.theLoop)); trd.Interrupt(); trd.Start(); while(true) { if(Console.ReadKey().KeyChar == 'q') { trd.Interrupt(); Environment.Exit(1); } Thread.Sleep(1); } }
public void Exchange_InterruptedException() { Exchanger e = new Exchanger(); Thread t = new Thread(new AnonymousClassRunnable4(e).Run); t.Start(); Thread.Sleep(Delays.Short); t.Interrupt(); t.Join(); }
public static void ForceStop(ref Thread thread, bool setNull) { try { if (thread != null && thread.IsAlive) { //force stop try { thread.Interrupt(); } catch (ThreadInterruptedException ex) { Log.WarnFormat("thread {0} Interrupt error : {1}", thread.Name, ex.Message); try { thread.Abort(); } catch (System.Exception ex1) { Log.WarnFormat("thread {0} Abort error : {1}", thread.Name, ex1.Message); } } catch (System.Exception ex) { Log.WarnFormat("thread {0} Interrupt error : {1}", thread.Name, ex.Message); try { thread.Abort(); } catch (System.Exception ex1) { Log.WarnFormat("thread {0} Abort error : {1}", thread.Name, ex1.Message); } } finally { if (setNull) { thread = null; } } } else { if (setNull) { thread = null; } } } catch (System.Exception ex) { Log.Error("Not expectant exception : ", ex); throw ex; } }
void MainWindow_Closed(object sender, EventArgs e) { SaveImages = false; running = false; dbThread.Interrupt(); frameThread.Interrupt(); saver.CancelAsync(); framer.CancelAsync(); }
public void Cancel() { this.cancel = true; if (worker != null) { worker.Interrupt(); worker.Join(); worker = null; } }
public void Cancel() { if (remuxThread.IsAlive) { remuxThread.Interrupt(); } try { File.Delete(this.outputFilepath); } catch { } }
public static void SearchCamersAsync() { Thread t = new Thread(DoSearch); t.IsBackground = true; UdpClient udp = new UdpClient(PCPort); t.Start(udp); Thread.Sleep(3000); t.Interrupt(); t.Join(); }
public static void StartWithThread(System.Threading.ThreadStart s, int timeout_second, string message) { var performed = false; while (!performed) { var tr = new System.Threading.Thread(s); try { tr.Start(); var co = 1; while (co < timeout_second + 1) { System.Threading.Thread.Sleep(1000); if (co > 1) { Console.SetCursorPosition(0, Console.CursorTop - 1); } Console.WriteLine($"{message} {co} second"); if (tr.ThreadState == ThreadState.Stopped) { performed = true; break; } co++; } if (!performed) { tr.Interrupt(); MyConsole.WriteLine_Error($"{message} not ended on {timeout_second} seconds - restarting on 10 seconds -------\n"); MyThread.GenerateConsoleWaiting(10); } if (performed) { MyConsole.WriteLine_Succ(message + $" Ended in {co} seconds !!!"); } } catch (Exception ex) { MyConsole.WriteLine_Exception("error in executing " + message, ex); throw new Exception(ex.Message); } } }
private static void MenuOpcoes(Thread thread) { Console.Clear(); Console.WriteLine("╔═══════════════════════════════════╗"); Console.WriteLine("║ Informe a opcao desejada: ║"); Console.WriteLine("║ 1- START ║"); Console.WriteLine("║ 2- PAUSE ║"); Console.WriteLine("║ 3- RESUME ║"); Console.WriteLine("║ 4- EXIT ║"); Console.WriteLine("╚═══════════════════════════════════╝"); opcao = int.Parse(Console.ReadLine()); switch (opcao) { case 1: Console.Clear(); thread.Start(); //Console.WriteLine("Start..."); //Console.ReadKey(); MenuOpcoes(thread); break; case 2: Console.Clear(); thread.Interrupt(); //Console.WriteLine("Pause..."); //Console.ReadKey(); MenuOpcoes(thread); break; case 3: Console.Clear(); thread.Resume(); //Console.WriteLine("Resume..."); //Console.ReadKey(); MenuOpcoes(thread); break; case 4: Console.Clear(); thread.Suspend(); //Console.WriteLine("Suspend"); //Console.ReadKey(); MenuOpcoes(thread); break; default: Console.WriteLine("Este comando nao e valido!Tente novamente."); break; } }
public void CanStopConsumerSide() { queue = new ProducerConsumerQueue(); dequeuedMsg = "This will be null if we break out of dequeue and return a null msg"; ThreadStart consumerMethod = new ThreadStart(runner); Thread consumerThread = new Thread(consumerMethod); consumerThread.Start(); Thread.Sleep(500); consumerThread.Interrupt(); consumerThread.Join(); Thread.Sleep(500); Assert.IsNull(dequeuedMsg); }
public void Run() { StayAwake sa = new StayAwake(); Thread newThread = new Thread(new ThreadStart(sa.ThreadMethod)); newThread.Name = "newThread"; newThread.Start(); Thread.Sleep(1000); newThread.Interrupt(); Console.WriteLine("Main thread call interrupt."); sa.SleepSwitch = true; newThread.Join(); }
private void Stop() { if (cancelled) { if (remuxThread.IsAlive) { remuxThread.Interrupt(); } File.Delete(newFilepath); } GLib.Source.Remove(timeout); dialog.Destroy(); }
static void Main() { ManualResetEventSlim mReset = new ManualResetEventSlim(); Uri uri = null; Thread hosting = new Thread(() => { #if DEBUG Thread.CurrentThread.Name = "ServiceHost"; #endif using (ServiceHost serviceHost = new ServiceHost(typeof(ChatServiceProject.ChatService))) { // Open the ServiceHost to create listeners and start listening for messages. serviceHost.Open(); MessageBox.Show("[SERVICE] Service is starting!"); uri = serviceHost.Description.Endpoints.SingleOrDefault( p => p.Contract.Name != "IMetadataExchange").Address.Uri; mReset.Set(); lock (serviceHost) { try { Monitor.Wait(serviceHost); } catch (ThreadInterruptedException) { MessageBox.Show("[SERVICE] Service is ending!"); } } } }); hosting.Start(); mReset.Wait(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ChatForm form = new ChatForm(uri); form.Closed += (_, p) => hosting.Interrupt(); Application.Run(form); }
public void AwaitNanos_Interrupt() { ReentrantReadWriteLock myLock = new ReentrantReadWriteLock(); ICondition c = myLock.WriterLock.NewCondition(); Thread t = new Thread(new AnonymousClassRunnable21(myLock, c).Run); t.Start(); Thread.Sleep(new TimeSpan((Int64) 10000*Delays.Short.Milliseconds)); t.Interrupt(); t.Join(Delays.Short); Assert.IsFalse(t.IsAlive); }
static void Main(string[] args) { Thread thr = new Thread(OnPrint); thr.Name = "Thread Two"; thr.Start(); Thread.Sleep(1000); /*Interrupt thread*/ thr.Interrupt(); thr.Join(); Console.WriteLine("Main thread terminating"); Console.ReadLine(); }
/// <summary> /// Interrupt the buffering thread, either stop or seek should have been set beforehand. </summary> /// <returns> True if there was a thread to interrupt. </returns> public virtual bool interrupt() { lock (actionSynchronizer) { System.Threading.Thread thread = playingThread.get(); if (thread != null) { thread.Interrupt(); return(true); } return(false); } }
/// <summary> /// Do our best to kill a thread, passing state info /// </summary> /// <param name="thread">The thread to kill</param> /// <param name="stateInfo">Info for the ThreadAbortException handler</param> public static void Kill(Thread thread, object stateInfo) { try { if (stateInfo == null) thread.Abort(); else thread.Abort(stateInfo); } catch (ThreadStateException) { } if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 ) thread.Interrupt(); }
public void ReplacementAfterExchange() { Exchanger e = new Exchanger(); Thread t1 = new Thread(new AnonymousClassRunnable7(e).Run); Thread t2 = new Thread(new AnonymousClassRunnable8(e).Run); Thread t3 = new Thread(new AnonymousClassRunnable9(e).Run); t1.Start(); t2.Start(); t3.Start(); Thread.Sleep(Delays.Short); t1.Interrupt(); t1.Join(); t2.Join(); t3.Join(); }
public void TestBlockingReceiveWithTimeout() { QueueChannel channel = new QueueChannel(); AtomicBoolean receiveInterrupted = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new ThreadStart(delegate { IMessage message = channel.Receive(new TimeSpan(10000)); receiveInterrupted.Value = true; Assert.IsTrue(message == null); latch.CountDown(); })); t.Start(); //Assert.IsFalse(receiveInterrupted.Value); t.Interrupt(); latch.Await(); Assert.IsTrue(receiveInterrupted.Value); }
/// <summary> /// Do our best to kill a thread, passing state info /// </summary> /// <param name="thread">The thread to kill</param> /// <param name="stateInfo">Info for the ThreadAbortException handler</param> public static void Kill(Thread thread, object stateInfo) { try { if (stateInfo == null) thread.Abort(); else thread.Abort(stateInfo); } catch (ThreadStateException) { // Although obsolete, this use of Resume() takes care of // the odd case where a ThreadStateException is received. thread.Resume(); } if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 ) thread.Interrupt(); }
public void Interrupt_thread() { var t = new Thread(() => { try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException e) { Console.Write("Forcibly ..."); } Console.WriteLine("Woken!"); }); t.Start(); t.Interrupt(); }
public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom) { try { if (tachyThread != null) { stopTachyThreadProc = true; tachyThread.Interrupt(); if (!tachyThread.Join(5000)) { tachyThread.Abort(); } } } catch (System.Exception e) { MessageBox.Show(e.Message + "\r\n\r\n" + e.InnerException + "\r\n\r\n" + e.StackTrace); } }
public void stop() { lock (actionSynchronizer) { System.Threading.Thread thread = playingThread.get(); if (thread != null) { log.LogDebug("Requesting stop for track {}", audioTrack.Identifier); isStopping.compareAndSet(false, true); thread.Interrupt(); } else { log.LogDebug("Tried to stop track {} which is not playing.", audioTrack.Identifier); } } }
/// <summary> /// Do our best to kill a thread, passing state info /// </summary> /// <param name="thread">The thread to kill</param> /// <param name="stateInfo">Info for the ThreadAbortException handler</param> public static void Kill(Thread thread, object stateInfo) { try { if (stateInfo == null) thread.Abort(); else thread.Abort(stateInfo); } catch (ThreadStateException) { // This is deprecated but still needed in this case // in order to kill the thread. The warning can't // be disabled because the #pragma directive is not // recognized by the .NET 1.1 compiler. thread.Resume(); } if ( (thread.ThreadState & ThreadState.WaitSleepJoin) != 0 ) thread.Interrupt(); }
public void Disconnect() { stopThreads = true; inProc.Interrupt(); outProc.Abort(); inProc.Abort(); outProc.Abort(); sock.Close(); commandQueue = new Queue <string>(); recievedMsgs = new List <string>(); buffer = string.Empty; if (GameObject.FindObjectOfType <TwitchLogin>() != null) { TwitchLogin[] l = GameObject.FindObjectsOfType <TwitchLogin>(); foreach (var L in l) { L.Disconnect(); hasBeenDisconnected = true; } } Debug.Log("Chat Disconnected"); }