c# thread數線程的創建


1、

1
2
3
4
5
6
Thread thread = new Thread( new ThreadStart(getpic));
thread.Start();
private void showmessage()
{
Console.WriteLine( "hello world" );
}

2、帶一個參數的線程

使用ParameterizedThreadStart,調用 System.Threading.Thread.Start(System.Object) 重載方法時將包含數據的對象傳遞給線程。

注意傳遞的參數只能是object類型,不過可以進行強制類型轉換。

 
1
2
3
4
5
6
7
8
Thread thread = new Thread( new ParameterizedThreadStart(showmessage));
string o = "hello" ;
thread.Start(( object )o);
private static void showmessage( object message)
{
string temp = ( string )message;
Console.WriteLine(message);
}

3、帶兩個及以上參數的線程

這時候可以將線程執行的方法和參數都封裝到一個類里邊,通過實例化該類,方法就可以調用屬性來盡享傳遞參數。

例如如下程序,想傳入兩個string變量,然后打印輸出。

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ThreadTest
{
private string str1;
private string str2;
public ThreadTest( string a, string b)
{
str1 = a;
str2 = b;
}
public void ThreadProc()
{
Console.WriteLine(str1 + str2);
}
}
public class Example {
public static void Main()
{
ThreadTest tt = new ThreadTest( "hello " , "world" );
Thread thread = new Thread( new ThreadStart(tt.ThreadProc));
thread.Start();
}
}

除了使用類還可以用hashtable、list、dictionary 等集合來傳參 ,在方法里進行強制轉換。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM