2012-12-26 78 views
0

我將如何去在C#中創建一個線程?在C#中創建一個線程#

在java中我要麼實現Runnable接口

class MyThread implements Runnable{ 
public void run(){ 
//metthod 
} 

然後

MyThread mt = new MyThread; 
Thread tt = new Thread(mt); 
tt.start() 

或者我可以簡單地擴展了Thread類

class MyThread extends Thread{ 
public void run(){ 
//method body 
} 

然後

MyThread mt = new MyThread 
mt.start(); 
+4

刪除'[java]'作爲答案不是關於Java(它只在問題中提到) –

+1

有很多方法可以這樣做。我建議看看Josef Albahari的[Threading in C#](http://www.albahari.com/threading/)。這是一個很好的入門書,雖然有些過時(例如TPL不會被提及)。 – Oded

+1

如果您嘗試使用您最喜愛的搜索引擎搜索「C#線程」,您會發現無數的鏈接列表。當然,使用[MSDN](http://msdn.microsoft.com/zh-cn/library/ms173178(VS.80))開始。aspx) – Steve

回答

6

不,與Java相反,.NET不能擴展Thread類,因爲它是封閉的。

因此,爲了在一個新的線程的最簡單的方式是手動生成一個新的線程,並把它傳遞給被執行的功能(在此情況下匿名功能)執行功能:

Thread thread = new Thread(() => 
{ 
    // put the code here that you want to be executed in a new thread 
}); 
thread.Start(); 

,或者如果你不希望使用匿名委託再定義一個方法:

public void SomeMethod() 
{ 
    // put the code here that you want to be executed in a new thread 
} 

,然後在同一類中啓動一個新線程傳遞參考這個方法:

Thread thread = new Thread(SomeMethod); 
thread.Start(); 

,如果你想將參數傳遞給方法:

public void SomeMethod(object someParameter) 
{ 
    // put the code here that you want to be executed in a new thread 
} 

然後:

Thread thread = new Thread(SomeMethod); 
thread.Start("this is some value"); 

這是一個在後臺線程來執行任務的土辦法。爲了避免支付高昂的價格創造新的線程,你可以使用一個線程從ThreadPool

ThreadPool.QueueUserWorkItem(() => 
{ 
    // put the code here that you want to be executed in a new thread 
}); 

或使用asynchronous delegate execution

Action someMethod =() => 
{ 
    // put the code here that you want to be executed in a new thread 
}; 
someMethod.BeginInvoke(ar => 
{ 
    ((Action)ar.AsyncState).EndInvoke(ar); 
}, someMethod); 

而另一個,更現代執行此類任務的方式是使用TPL(從.NET 4.0開始):

Task.Factory.StartNew(() => 
{ 
    // put the code here that you want to be executed in a new thread 
}); 

所以,是的,正如你所看到的,有許多技術可以用來在單獨的線程上運行一堆代碼。

+1

作爲附加信息,您還可以使用'Timer'線程類以指定的時間間隔重複創建一個線程。 – Joe

+4

@Joe,是的,正如我所說的,有像gazzilion方式在後臺線程上執行某些任務。人們已經寫了關於這個問題的整本書。在一個單一的答案中很難涵蓋它們。我只是給OP提供了一些提示,以便他可以繼續研究,並希望下次能夠提出更具體的問題。 –

+0

確實。我只是指出了定時器到OP,因爲它是有用的知道,並且也確保他不會在他的線程中添加某種睡眠以模仿定時器;) – Joe