2

Possible Duplicate:
Returning a value from thread?

I have this code:

//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);

The problem is that ExecuteCommandSync returns a string.

How can i capture the string that is returned and return it?

Community
  • 1
  • 1
Danpe
  • 18,668
  • 21
  • 96
  • 131
  • 2
    assign the string on class level variable (field)? – Predator Jul 04 '11 at 18:52
  • http://stackoverflow.com/questions/1314155/returning-a-value-from-thread – adt Jul 04 '11 at 18:54
  • You're going to need an IAsyncResult to share data between threads. but by its nature an async function cannot return data. I can write you a sample for safely sharing data between threads. What application type is this Console? WinForm? WPF? Web? – Glenn Ferrie Jul 04 '11 at 18:57

4 Answers4

6

I would recommend looking into the TPL in .NET 4. It would allow you to do:

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

Later, when you need the result, you can access it (which will block if the method isn't completed), by doing:

string results = resultTask.Result;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

You cannot use ParameterizedThreadStart if the callback returns something. Try the following:

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);

Also notice that objThread.Start starts the thread and returns immediately. So make sure that the hosting process doesn't end before the thread finishes executing as because you made it a background thread it will be aborted. Otherwise don't make it background thread.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

From Threading in C# by Joseph Albahari

you can do :

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);
flacours
  • 41
  • 2
0

You can't.

The thread runs in the background, and only finishes some time after the rest of your code.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964