本文整理匯總了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
}
示例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();
}
}
}
}
}
示例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;
}
示例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);
}
}
示例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;
}
}
示例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();
}
示例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();
}
示例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);
}
示例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 ();
}
示例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);
}
示例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;
}
示例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;
}
示例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();
}
示例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();
}
示例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);
}
}