【发布时间】:2011-03-13 10:14:20
【问题描述】:
我只是一个初学者。“ParameterizedThreadStart”接受单个对象作为参数。
有没有其他的委托签名可以让我
(1) 在线程上传递参数(可变数量的参数)?
(2) 支持列表等泛型参数?
【问题讨论】:
标签: c# multithreading delegates
我只是一个初学者。“ParameterizedThreadStart”接受单个对象作为参数。
有没有其他的委托签名可以让我
(1) 在线程上传递参数(可变数量的参数)?
(2) 支持列表等泛型参数?
【问题讨论】:
标签: c# multithreading delegates
你可以用一个对象做任何你想做的事情。只需定义一个类来包装你感兴趣的参数即可:
class ThreadState
{
public ThreadState()
{
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
// ...
ParameterizedThreadStart start = delegate(object objThreadState)
{
// cast to your actual object type
ThreadState state = (ThreadState)objThreadState;
// ... now do anything you want with it ...
};
【讨论】:
您可以使用 Delegate.BeginInvoke 和 EndInvoke 来传递您想要的任何参数
delegate long MyFuncDelegate(int N );
MyFuncDelegate cpn = new MyFuncDelegate(MyFunc);
IAsyncResult ar = cpn.BeginInvoke( 3, null, null );
// Do some stuff
while( !ar.IsCompleted )
{
// Do some stuff
}
// we now know that the call is
// complete as IsCompleted has
// returned true
long answer = cpn.EndInvoke(ar);
【讨论】:
顺便说一句,使用泛型,定义具有字段的类(例如 Doer(Of T1)、Doer(Of T1, T2) 等很有用,例如V1 As T1,V2 As T2 等,以及 theAction As Action(Of T1, T2) 等以及调用 theAction(V1, V2) 和静态工厂方法的单个方法 Exec(void) 等。即使在 VS2005 中,这也使得组装一个调用具有适当参数的函数的 MethodInvoker 变得非常容易。
【讨论】: