【发布时间】:2012-05-19 01:49:18
【问题描述】:
我想在一个线程中执行一个方法。该方法有多个参数并期望返回值。有人可以帮忙吗?
【问题讨论】:
-
你能使用 .NET 4.0 吗?
标签: c#
我想在一个线程中执行一个方法。该方法有多个参数并期望返回值。有人可以帮忙吗?
【问题讨论】:
标签: c#
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);
【讨论】:
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) { ... }
【讨论】:
DoSomethingWithTheValue 不会在主线程上执行。只需调用Thread thread = new Thread(() => DoSomething(YourMethod(param1, param2))) 即可获得相同的结果