最終更新:2018-05-07 (月) 14:36:42 (2175d)  

System.Threading.Thread
Top / System.Threading.Thread

スレッドを作成および制御し、そのスレッドの優先順位の設定およびステータスの取得を行います。

引数

System.Threading.ThreadStart (デリゲート)

  • Represents the method that executes on a Thread.

普通の書き方

  • System.Threading.Thread t1 = new System.Threading.Thread(
        ThreadStart(処理する関数名));

匿名メソッド (C♯ 2.0)

  • ThreadStartデリゲートへの暗黙の変換
    System.Threading.Thread t1 = new System.Threading.Thread(
        delegate()
        {
            System.Console.Write("Hello, ");
            System.Console.WriteLine("World!");
        });

ラムダ式 (C♯ 3.0)

  • System.Threading.Thread t1 = new System.Threading.Thread(
        () => {
            System.Console.Write("Hello, ");
            System.Console.WriteLine("World!");
        });
    });

使い方

  • using System;
    class Program{
    
    	private static void threadFunc(){
    		try{
    			//ここでスレッドの処理
    			System.Threading.Thread.Sleep(1000);
    		}catch{
    			//スレッド終了
    		}
    	}
    
    	static void Main(string[] args){
    		//スレッドの宣言
    		System.Threading.Thread thread;
    		//スレッドの作成
    		//コンストラクタの引数はThreadStart型のデリゲート
    		thread = new System.Threading.Thread(new System.Threading.ThreadStart(threadFunc));
    		//スレッドの開始
    		thread.Start();
    
    	}
    
    }

メモ

値の受け渡し

//コールバック用のデリゲート
public delegate void threadFinishedCallback(string text);

class threadClass{
	//スレッドに渡されるデータ用
	private string msg;
	private int wait;
	private threadFinishedCallback callback;//デリゲートを格納する変数
	//コンストラクタ
	public threadClass(string msg,int wait,threadFinishedCallback callbackDelegate){
		this.msg = msg;
		this.wait = wait;
		this.callback = callbackDelegate;//コールバック用のデリゲート
	}

	public void threadFunc(){
		try{
			//ここでスレッドの処理
			Console.WriteLine(this.msg);
			System.Threading.Thread.Sleep(this.wait);
		}catch{
			//スレッド終了
			//デリゲートを呼び出す
			callback("スレッド終了");
		}
	}

}

class Program{

	static void Main(string[] args){
		//スレッドの宣言
		System.Threading.Thread thread;
		//オブジェクト
		threadClass objThread = new threadClass("ほげほげ",1000,new threadFinishedCallback(threadFinish));
		//スレッドの作成
		//コンストラクタの引数はThreadStart型のデリゲート
		thread = new System.Threading.Thread(new System.Threading.ThreadStart(objThread.threadFunc));
		//バックグラウンドスレッドにする場合
		//thread.IsBackground=true;
		//スレッドの開始
		thread.Start();

	}

	//コールバックで呼び出される関数
	public static void threadFinish(string text){
		Console.WriteLine(text);
	}

}