0

I would like to execute a method in a thread. The method has multiple arguments and expects return value. Can anyone help?

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
Channa
  • 83
  • 1
  • 2
  • 7
  • Are you able to use .NET 4.0? – Alex May 10 '12 at 13:21
  • http://stackoverflow.com/questions/1314155/returning-a-value-from-thread OR http://stackoverflow.com/questions/8860141/c-sharp-thread-method-return-a-value – Robar May 10 '12 at 13:23

2 Answers2

4
Thread thread = new Thread(() => 
       {
          var result = YourMethod(param1, param2);
          // process result here (does not invoked on your main thread)
       });

If you need to return result to main thread, then consider using Task (C# 4) instead:

var task = new Task<ReturnValueType>(() => YourMethod(param1, param2));
task.Start();

// later you can get value by calling task.Result;

Or with previous version of C#

Func<Param1Type, Param2Type, ReturnValueType> func = YourMethod;            
IAsyncResult ar = func.BeginInvoke(param1, param2, null, null);
ar.AsyncWaitHandle.WaitOne();
var result = func.EndInvoke(ar);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1
Func<string, int, bool> func = SomeMethod;
AsyncCallback callback = ar => { bool retValue = func.EndInvoke(ar); DoSomethingWithTheValue(retValue };
func.BeginInvoke("hello", 42, callback, null);


...

bool SomeMethod(string param1, int param2) { ... }
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • In this case `DoSomethingWithTheValue` will not be executed on main thread. Same result you can achieve simply by calling `Thread thread = new Thread(() => DoSomething(YourMethod(param1, param2)))` – Sergey Berezovskiy May 10 '12 at 14:06