1、無引數執行緒的建立
thread thread = new thread(new2、帶乙個引數的執行緒threadstart(getpic));
thread.start();
private
void
showmessage()
使用parameterizedthreadstart,呼叫 system.threading.thread.start(system.object) 過載方法時將包含資料的物件傳遞給執行緒。
注意傳遞的引數只能是object型別,不過可以進行強制型別轉換。
thread thread = new thread(new3、帶兩個及以上引數的執行緒parameterizedthreadstart(showmessage));
string o = "
hello";
thread.start((
object
)o);
private
static
void showmessage(object
message)
這時候可以將執行緒執行的方法和引數都封裝到乙個類裡邊,通過例項化該類,方法就可以呼叫屬性來盡享傳遞引數。
例如如下程式,想傳入兩個string變數,然後列印輸出。
publicclass
threadtest
public
void
threadproc()
}public
class
example
}4.將執行緒執行的方法和引數都封裝到乙個類裡面。通過例項化該類,方法就可以呼叫屬性來實現間接的型別安全地傳遞引數。
具體**如下(本示例來自msdn)
usingview code 方法一:在vs2003中,也不能直接訪問,參看system;
using
system.threading;
//threadwithstate 類裡包含了將要執行的任務以及執行任務的方法
public
class
threadwithstate
//要丟給執行緒執行的方法,本處無返回型別就是為了能讓threadstart來呼叫
public
void
threadproc()
}//用來呼叫上面方法的類,是本例執行的入口
public
class
example .
", 42
);
//建立執行任務的執行緒,並執行
thread t = new thread(new
threadstart(tws.threadproc));
t.start();
console.writeline(
"main thread does some work, then waits.");
t.join();
console.writeline(
"independent task has completed; main thread ends.
"); }}
一般來說,直接在子執行緒中對窗體上的控制項操作是會出現異常,這是由於子執行緒和執行窗體的執行緒是不同的空間,因此想要在子執行緒來操作窗體上的控制項,是不可能 簡單的通過控制項物件名來操作,但不是說不能進行操作,微軟提供了invoke的方法,其作用就是讓子執行緒告訴窗體執行緒來完成相應的控制項操作。
現在用乙個用執行緒控制的程序條來說明,大致的步驟如下:
1.建立invoke函式,大致如下:
///
/// delegate function be invoked by main thread
///
private void invokefun()
2.子執行緒入口函式:
///
/// thread function inte***ce
///
private void threadfun() }
3.建立子執行緒:
thread thdprocess = new thread(new threadstart(threadfun));
thdprocess.start();
備註:
using system.threading;
private system.windows.forms.progressbar prgbar;
方法二:
加入該句:control.checkforillegalcrossthreadcalls = false 取消線執行緒安全保護模式!
方法三:帶引數
使用類、類的方法或類的屬性都可以向執行緒傳遞引數:
public class url**********
public void download()
}[... 在另乙個類中使用它們...]
url********** ********** = new url********** (yoururl);
new thread (new threadstart (**********.download)).start();
注意引數是如何傳遞的。
方法四:帶引數
threadstart starter = delegate ;
new thread(starter).start();
//使用執行緒池
waitcallback callback = delegate (object state) ;
threadpool.queueuserworkitem (callback, yoururl);
方法五:帶引數
thread t =new thread (new parameterizedthreadstart(downloadurl));
t.start (myurl);
static void downloadurl(object url)
C 中建立執行緒,建立帶引數的執行緒
執行緒操作主要用到thread類,他是定義在system.threading.dll下。使用時需要新增這乙個引用。該類提供給我們四個過載的構造函 建構函式定義 無引數委託 securitysafecritical public thread threadstart start securitysaf...
帶引數的執行緒
namespace aaaaaa private static void b object obj obj.tostring 2 帶多個引數的 由於thread預設只提供了這兩種建構函式,如果需要傳遞多個引數,我們可以自己將引數作為類的屬性。定義類的物件時候例項化這個屬性,然後進行操作。namesp...
帶引數執行緒
執行緒操作主要用到thread類,他是定義在system.threading.dll下。使用時需要新增這乙個引用。該類提供給我們四個過載的建構函式。一 不帶引數的 結果顯示method a 二 帶乙個引數的 由於parameterizedthreadstart要求引數型別必須為object,所以定義...