2012-10-04 50 views
0

我想配置我的線程爲後臺線程,爲什麼這個屬性在我的線程中失蹤?C#後臺線程屬性丟失

ThreadStart starter = delegate { openAdapterForStatistics(_device); }; 
    new Thread(starter).Start(); 

public void openAdapterForStatistics(PacketDevice selectedOutputDevice) 
{ 
    using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter 
    { 
     statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode     
     statCommunicator.ReceiveStatistics(0, statisticsHandler); 

    } 
} 

我有嘗試:

Thread thread = new Thread(openAdapterForStatistics(_device)); 

,但我有2編譯錯誤:

  1. 爲「System.Threading.Thread.Thread的最佳重載的方法匹配(系統.Threading.ThreadStart)'有一些無效參數
  2. 參數1:無法從'void'轉換爲'System.Threading.ThreadStar T」

,我不知道爲什麼

+0

我認爲這是因爲你應該通過一個代表參數化函數。不是功能。在你的情況下啓動器。 – Juvil

+0

嘗試'線程線程=新線程((()=> openAdapterForStatistics(_device));' –

回答

1

關於後臺的事情,我不看你怎麼想到把它,因爲你不守的線程的引用。應該是這樣的:

ThreadStart starter = delegate { openAdapterForStatistics(_device); }; 
Thread t = new Thread(starter); 
t.IsBackground = true; 
t.Start(); 

Thread thread = new Thread(openAdapterForStatistics(_device)); 

不會起作用,因爲你應該在需要object作爲參數的方法來傳遞,而你實際上傳遞的結果方法調用方法調用。所以,你可以這樣做:

public void openAdapterForStatistics(object param) 
{ 
    PacketDevice selectedOutputDevice = (PacketDevice)param; 
    using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter 
    { 
     statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode     
     statCommunicator.ReceiveStatistics(0, statisticsHandler); 

    } 
} 

和:

Thread t = new Thread(openAdapterForStatistics); 
t.IsBackground = true; 
t.Start(_device); 
+0

坦克很多爲您的答案! –

0

您應該使用BackgroundWorker類,這是專門爲喜歡你的情況下使用而設計的。您希望在後臺完成的任務。

0
PacketDevice selectedOutputDeviceValue = [some value here]; 
Thread wt = new Thread(new ParameterizedThreadStart(this.openAdapterForStatistics)); 
wt.Start(selectedOutputDeviceValue); 
+0

這實際上不起作用,因爲'ParameterizedThreadStart'需要一個'object'參數。 – Tudor

+0

簡單,修改方法openAdapterForStatistics(object _obj)來接受對象。 – Juvil