別スレッドで処理を実行・停止するサンプル

Form1.cs
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7. namespace WindowsFormsApplication1
  8. {
  9.     public partial class Form1 : Form
  10.     {
  11.         Thread thread = null;
  12.         public Form1()
  13.         {
  14.             InitializeComponent();
  15.         }
  16.         /// <summary>
  17.         /// 実行
  18.         /// </summary>
  19.         /// <param name="sender"></param>
  20.         /// <param name="e"></param>
  21.         private void exeBtn_Click(object sender, EventArgs e)
  22.         {
  23.             if (thread == null)
  24.             {
  25.                 threadState.Text = "実行中";
  26.                 textBox1.Text = "";
  27.                 ThreadTest.cnt = 0;
  28.                 ThreadTest.exeFlg = true;
  29.                 thread = new Thread(new ThreadStart(ThreadTest.countUp));
  30.                 // 別スレッドの処理開始
  31.                 thread.Start();
  32.             }
  33.         }
  34.         /// <summary>
  35.         /// 停止
  36.         /// </summary>
  37.         /// <param name="sender"></param>
  38.         /// <param name="e"></param>
  39.         private void stopBtn_Click(object sender, EventArgs e)
  40.         {
  41.             threadState.Text = "停止中";
  42.             ThreadTest.exeFlg = false;
  43.             textBox1.Text = ThreadTest.cnt.ToString();
  44.             // スレッド破棄
  45.             thread.Abort();
  46.             thread = null;
  47.         }
  48.     }
  49. }
ThreadTest.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7. namespace WindowsFormsApplication1
  8. {
  9.     class ThreadTest
  10.     {
  11.         public static int cnt = 0;
  12.         public static bool exeFlg = false;
  13.         /// <summary>
  14.         /// 別スレッド用処理
  15.         /// </summary>
  16.         public static void countUp()
  17.         {
  18.             // 停止ボタンが押されるまで処理
  19.             while (exeFlg)
  20.             {
  21.                 cnt++;
  22.                 // 1秒毎に加算するようにスリープを設定
  23.                 Thread.Sleep(1000);
  24.             }
  25.         }
  26.     }
  27. }

image

実行ファイルダウンロード

戻る