Abort a Thread in C#

In this article, I will explain how to abort a thread by using Thread.Abort method in .NET Framework.
  • 7749
Introduction

To abort a thread is very simple in C#. It is used when we want to abort a thread in the program. The thread class's Abort method is called to abort a thread. Make sure you check the IsAliveproperty before Abort.

if (Thread.IsAlive)

   {

    Thread.Abort();

   } 

 

Example

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading; 

namespace Threadabort

{

    class Program

    {

        static void Main(string[] args)

        {

            Thread th = new Thread(WriteY);

            if (th.IsAlive)

            {

                th.Start();

                th.Abort();

            }

 

            for (int i = 0; i <= 10; i++)

            {

                Console.WriteLine("Hello");

            }

            Console.ReadLine();

        }

          static void WriteY()

        {

            for (int i = 0; i <= 9; i++)

            {

                Console.WriteLine("Hi");

            }

        }

    }

}

 

Output


Clipboard252.jpg

© 2020 DotNetHeaven. All rights reserved.