Java的Thread是利用繼承Thread或是實作Runable來實現的,而C#確是不一樣的,
C#利用一個new System.Threading.Thread物件,建構時傳入想要在執行緒裡動作的事件,
啟動方法跟Java一樣,利用Start()來開始這個執行序,
System.Threading.Thread t = new System.Threading.Thread(要執行的Function名稱);
啟動方式
t.Start();
那如果有參數要傳入呢?
可以撰寫一個Class,先建構及設定好需要的參數,再把這個class實作的物件及方法傳入實作的System.Threading.Thread物件裡
就可以啦
Object x = new Object();
System.Threading.Thread t = new System.Threading.Thread(x.方法);
這裡有一個範例可以參考一下
先建立一個Class,名叫thread1
利用無窮迴圈讓內容一直跑,再利用Sleep(毫秒)來使其停一秒再執行。
================================================
先宣告thread物件
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class thread1 { private String title; public thread1(String title) { this.title = title; } public void runMe() { while(true) { Console.Write(title+"\r\n"); System.Threading.Thread.Sleep(1000); } } }}================================================
再來只要再需要的地方啟動它就可以啦
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { thread1 obj = new thread1("我還可以傳入參數"); Thread t = new Thread(obj.runMe); t.Start(); } }}