2011-07-04 3 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

私はそれはあなたができるようになる、.NET 4にTPLに探してお勧めします:あなたが結果を必要とするとき

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

その後、あなたはそれにアクセスすることができます(法のISN場合はブロックしますました

string results = resultTask.Result; 
1

Threading in C# by Joseph Albahari

からあなたが行うことができます:「tが行うことにより、)完成

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); 
関連する問題