当前位置: 首页>>代码示例>>C#>>正文


C# Thread.Interrupt方法代码示例

本文整理汇总了C#中System.Threading.Thread.Interrupt方法的典型用法代码示例。如果您正苦于以下问题:C# Thread.Interrupt方法的具体用法?C# Thread.Interrupt怎么用?C# Thread.Interrupt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.Thread的用法示例。


在下文中一共展示了Thread.Interrupt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Kill

        /// <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
        }
开发者ID:alfeg,项目名称:nunit,代码行数:30,代码来源:ThreadUtility.cs

示例2: TestNoTimeoutConsumer

 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();
                 }
             }
         }
     }
 }
开发者ID:Redi0,项目名称:meijing-ui,代码行数:30,代码来源:ConsumerTest.cs

示例3: RunWithTimeout

 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;
 }
开发者ID:molec1,项目名称:MySPM_NewParsers,代码行数:27,代码来源:DataDBURLQueue.cs

示例4: TestThrowExceptionAtInsert

        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);

            }
        }
开发者ID:alexgyori,项目名称:PdfConversion,代码行数:27,代码来源:UnitTestPoller.cs

示例5: ConnectTo_GivenTheOutletHasASender_ThrowsAnInvalidOperationException

        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;
            }
        }
开发者ID:michaelbradley91,项目名称:Pipes,代码行数:29,代码来源:SimpleOutletTests.cs

示例6: SimpleTest

        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();
        }
开发者ID:netcasewqs,项目名称:nlite,代码行数:33,代码来源:ThreadTest.cs

示例7: RedirectionFinalizationTest

 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();
 }
开发者ID:dupdob,项目名称:SHON,代码行数:26,代码来源:RedirectionTest.cs

示例8: MenuComandos

        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);
        }
开发者ID:luisflv,项目名称:SistemasDistribuidos,代码行数:35,代码来源:Program.cs

示例9: Execute

        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} [email protected]{1}", Application.Configuration.SSHPrivateKey, dev.IP));
                connection.Interrupt ();
            } else {
                foreach (var i in errors) {
                    Console.Error.WriteLine (i);
                }
            }
            connection.Join ();
        }
开发者ID:juslee,项目名称:monoberry,代码行数:31,代码来源:Shell.cs

示例10: Interrupt_thread_does_not_throw_if_not_blocked

        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);
        }
开发者ID:simonlaroche,项目名称:DumpingGrounds,代码行数:27,代码来源:InterruptAbortSample.cs

示例11: GetFilesLockedBy

        /// <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;
        }
开发者ID:BruceNielsen,项目名称:_V4.7-Proxy,代码行数:35,代码来源:CheckIfFileIsLockedByProcess.cs

示例12: Run

 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;
 }
开发者ID:utlww,项目名称:topcoder,代码行数:28,代码来源:18.3.Requester.cs

示例13: Main

        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();
        }
开发者ID:guogongjun,项目名称:Blink,代码行数:31,代码来源:Program.cs

示例14: TimedExchange_InterruptedException

 public void TimedExchange_InterruptedException()
 {
     Exchanger e = new Exchanger();
     Thread t = new Thread(new AnonymousClassRunnable5(e).Run);
     t.Start();
     t.Interrupt();
     t.Join();
 }
开发者ID:rlxrlxrlx,项目名称:spring-net-threading,代码行数:8,代码来源:ExchangerTests.cs

示例15: Main

        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);
            }
        }
开发者ID:thedancomplex,项目名称:Hubo-UDP-to-Serial--UDP2Serial-,代码行数:17,代码来源:Main.cs


注:本文中的System.Threading.Thread.Interrupt方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。