2011-07-04 73 views
2

可能重複:
Returning a value from thread?.NET線程返回值?

我有這樣的代碼:

//Asynchronously start the Thread to process the Execute command request. 
Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync)); 
//Make the thread as background thread. 
objThread.IsBackground = true; 
//Set the Priority of the thread. 
objThread.Priority = ThreadPriority.AboveNormal; 
//Start the thread. 
objThread.Start(command); 

的問題是,ExecuteCommandSync返回一個字符串。

如何捕獲返回的字符串並將其返回?

+2

在類級變量(字段)上分配字符串? – Predator

+0

http://stackoverflow.com/questions/1314155/returning-a-value-from-thread – adt

+0

你將需要一個IAsyncResult來在線程之間共享數據。但就其性質而言,異步函數不能返回數據。我可以給你寫一個樣本,以便在線程之間安全地共享數據。此控制檯有哪些應用程序類型? WinForm的? WPF?網? –

回答

3

如果回調返回某些內容,則不能使用ParameterizedThreadStart。請嘗試以下操作:

Thread objThread = new Thread(state => 
{ 
    string result = ExecuteCommandSync(state); 
    // TODO: do something with the returned result 
}); 
//Make the thread as background thread. 
objThread.IsBackground = true; 
//Set the Priority of the thread. 
objThread.Priority = ThreadPriority.AboveNormal; 
//Start the thread. 
objThread.Start(command); 

另請注意,objThread.Start將啓動線程並立即返回。因此,請確保宿主進程在線程完成執行之前不會結束,因爲您已將其作爲後臺線程來終止執行。否則,不要使它成爲後臺線程。

0

你不能。

線程在後臺運行,只在代碼的其餘部分完成一段時間。

6

我會建議尋找到TPL在.NET 4這將允許你這樣做:

Task<string> resultTask = Task.Factory.StartNew(() => ExecuteCommandSync(state)); 

以後,當你需要的結果,您可以訪問它(如果方法ISN這將阻止「T完成),這樣做:

string results = resultTask.Result; 
1

Threading in C# by Joseph Albahari

你可以這樣做:

static int Work(string s) { return s.Length; } 

static void Main(string[] args) 
{ 
    Func<string, int> method = Work; 
    IAsyncResult cookie = method.BeginInvoke ("test", null, null); 
    // 
    // ... here's where we can do other work in parallel... 
    // 
    int result = method.EndInvoke (cookie); 
    Console.WriteLine ("String length is: " + result);