C Method for Stopping Threads

  • 2021-07-26 08:45:29
  • OfStack

This article illustrates how C # stops threads. Share it for your reference. The specific implementation method is as follows:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinFormApp
{
 public partial class Form1 : Form
 {
  System.Threading.CancellationTokenSource cancel = new System.Threading.CancellationTokenSource();
  System.Threading.Thread[] thread;
  int len = 2;
  public Form1()
  {
   InitializeComponent();
   thread = new System.Threading.Thread[len];
  }
  void RunThread()
  {
   ThreadInvoke.SetEventInvokeValue(richTextBox1, " The thread is about to start running .");
   System.Threading.Thread t = null;
   for (int i = 0; i < len; i++)
   {
    t = new System.Threading.Thread(new System.Threading.ThreadStart(Sample));
    t.Name = "thread_0" + i.ToString();
    t.IsBackground = true;
    thread.SetValue(t, i);
    t.Start();
   }
  }
  void Sample()
  {
   string name = System.Threading.Thread.CurrentThread.Name;
   ThreadInvoke.SetEventInvokeValue(richTextBox1, " Running thread: " + name);
   while (true)
   {
    if (cancel.IsCancellationRequested)
    {
     ThreadInvoke.SetEventInvokeValue(richTextBox1, " Threads: " + name + "  Stop running ...");
     // Callback after thread is terminated 
     cancel.Token.Register(delegate
     {
      ThreadInvoke.SetEventInvokeValue(richTextBox1, " Threads: " + name + "  Callback function after stopping running ...");
     });
     break;
    }
   }
  }
  void ShowStatu()
  {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < len; i++)
   {
    if (thread[i].IsAlive == true)
    {
     sb.AppendLine(" Threads: " + thread[i].Name.ToString() + "  Still running ...");
    }
   }
   if (sb.ToString() == "")
   {
    sb.AppendLine(" Threads have all stopped ...");
   }
   richTextBox1.Text += sb.ToString();
  }
  /// <summary>
  ///  Start running threads 
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void button1_Click(object sender, EventArgs e)
  {
   RunThread();
  }
  /// <summary>
  ///  Display all thread states 
  /// </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)
  {
   cancel.Cancel();
  }
 }
}

I hope this article is helpful to everyone's C # programming.


Related articles: