我想在线程中执行一个方法。该方法有多个参数并期望返回值。任何人都可以帮忙吗?
问问题
210 次
2 回答
4
Thread thread = new Thread(() =>
{
var result = YourMethod(param1, param2);
// process result here (does not invoked on your main thread)
});
如果您需要将结果返回到主线程,请考虑改用 Task (C# 4):
var task = new Task<ReturnValueType>(() => YourMethod(param1, param2));
task.Start();
// later you can get value by calling task.Result;
或者使用以前版本的 C#
Func<Param1Type, Param2Type, ReturnValueType> func = YourMethod;
IAsyncResult ar = func.BeginInvoke(param1, param2, null, null);
ar.AsyncWaitHandle.WaitOne();
var result = func.EndInvoke(ar);
于 2012-05-10T13:19:50.557 回答
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) { ... }
于 2012-05-10T13:20:44.230 回答