0

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

2

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Servy just avoided in this case
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) { ... }

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.