C# 线程中的参数处理
我只是一个初学者。ParameterizedThreadStart接受单个对象作为参数 是否有其他代表签名允许我 1传递参数线程上参数的可变数目C# 线程中的参数处理,c#,multithreading,delegates,C#,Multithreading,Delegates,我只是一个初学者。ParameterizedThreadStart接受单个对象作为参数 是否有其他代表签名允许我 1传递参数线程上参数的可变数目 2支持诸如list?之类的通用参数。您可以使用Delegate.BeginInvoke和EndInvoke来传递所需的任何参数 delegate long MyFuncDelegate(int N ); MyFuncDelegate cpn = new MyFuncDelegate(MyFunc); IAsyncResult ar = cpn.B
2支持诸如list?之类的通用参数。您可以使用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);
您可以使用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);
你可以用一个对象做任何你想做的事情。只需定义一个类来包装您感兴趣的参数:
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 ...
};
你可以用一个对象做任何你想做的事情。只需定义一个类来包装您感兴趣的参数:
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 ...
};
顺便说一句,对于泛型,定义DoerOf T1、DoerOf T1、T2等类很有用,这些类的字段包括V1为T1、V2为T2等,Action为ActionOf T1、T2等,以及调用ActionV1、V2和静态工厂方法的单个方法Execvoid等。这使得使用适当参数调用函数的MethodInvoker非常容易,即使在VS2005中也是如此。顺便说一句,对于泛型,定义DoerOf T1、DoerOf T1、T2等类非常有用,这些类具有字段,例如V1作为T1、V2作为T2等,Action作为T1、T2等的Action,以及单个方法Execvoid,它调用ActionV1、V2和静态工厂方法。这使得组装MethodInvoker非常容易,即使在VS2005中,它也可以使用正确的参数调用函数。或者只传递一个对象数组。是的,你也可以传递一个数组,它更轻量级,但不太安全。真的帮了我很多忙。谢谢。或者只传递一个对象数组。是的,你也可以传递一个数组,这是更轻,但不太安全的类型。真的帮了我很多。谢谢。