2.マルチスレッド

マルチスレッド

  1. マルチスレッドは、ThreadingのTreadクラスを使用する。
  2. TreadクラスのコンストラクタはTreadStartデリゲートを引数に取る。
  3. TreadStartデリゲートにはスレッドで実行したいメソドを登録する。
  4. Treadを実行するにはTrearクラスのStartメソドを呼び出す。
  5. メインスレッド以外からメインスレッドのコントロールにアクセスする場合はControl.Invokeを使用する。
  6. Invokeメソドはデリゲートを引数に取り、其のデリゲートには実行したいメソドを登録する。


サンプルコード

        • using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MulutiTread
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();                    
       }

       //デリゲートそ宣言する
       delegate void MyDelegate();

       public void setTime()
       {
           //Invokeが必要な時はInvokeを使い、不必要の時は直接書き込む
           if (InvokeRequired)
              Invoke(new MyDelegate(DisplayTime));
           else
              DisplayTime();
       }

       void DisplayTime()
       {
           //現在の時刻を表示する
           label1.Text = DateTime.Now.ToString();
       }

       private void button1_Click(object sender, EventArgs e)
       {
           //メインスレッドから表示
           setTime();
       }

       private void button2_Click(object sender, EventArgs e)
       {
           //第2スレッドから表示
           Thread t1 = new Thread(new ThreadStart(setTime ));
           t1.Start();
       }
   }
}

最終更新:2009年08月18日 16:21