This article describes the method of stopping threads in C#. Share it for your reference. The specific implementation method is as follows:
using System; using ; using ; using ; using ; using ; using ; using ; namespace WinFormApp { public partial class Form1 : Form { cancel = new (); [] thread; int len = 2; public Form1() { InitializeComponent(); thread = new [len]; } void RunThread() { (richTextBox1, "The thread is about to start running."); t = null; for (int i = 0; i < len; i++) { t = new (new (Sample)); = "thread_0" + (); = true; (t, i); (); } } void Sample() { string name = ; (richTextBox1, "Running thread:" + name); while (true) { if () { (richTextBox1, "Thread:" + name + "Stop running..."); //Callback after thread is terminated (delegate { (richTextBox1, "Thread:" + name + "Callback function after stopping..."); }); break; } } } void ShowStatu() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (thread[i].IsAlive == true) { ("Thread:" + thread[i].() + " Still running..."); } } if (() == "") { ("The threads have all stopped..."); } += (); } /// <summary> /// Start running the thread /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { RunThread(); } /// <summary> /// Show all thread status /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { ShowStatu(); } /// <summary> /// Terminate all threads /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { (); } } }
I hope this article will be helpful to everyone's C# programming.