A running thread can be aborted using Thread.Abort method. When we abort a thread, a thread abort exception will be thrown in that thread.
using System;
using System.Threading;// Thread.Abort
class Program {
static void Main(string[] args) {
Console.WriteLine("Main Started");
var th = new Thread(Greet); // Create new thread
th.Start(new object[] { "Bob", "Good Morning" }); // Execute Greet method in the created thread
Thread.Sleep(500);
th.Abort();
Console.WriteLine("Main Completed");
Console.ReadKey();
}private static void Greet(object info) {
try {
Thread.Sleep(1000);
Console.WriteLine("Hi {0}, {1}!", (info as object[])[0], (info as object[])[1]);
Thread.Sleep(1000);
}
catch (ThreadAbortException) {
Console.WriteLine("Greet Aborted");
}
}
}
Output:
Main Started
Main Completed
Greet Aborted
No comments:
Post a Comment