Reputation: 83
I would like to execute a method in a thread. The method has multiple arguments and expects return value. Can anyone help?
Upvotes: 0
Views: 223
Reputation: 236218
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);
Upvotes: 4
Reputation: 292425
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) { ... }
Upvotes: 1