1

I am just a beginner."ParameterizedThreadStart" accepts single object as argument.

Is there any other delegate signature allows me to

(1) pass params (variable number of parameter) on thread?

(2) support generic parameters like list ?

3 Answers 3

5

You can do anything you want with a single object. Just define a class to wrap the parameters you are interested in:

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 ...
};
2
  • Or just pass an array of objects. Oct 10, 2009 at 17:47
  • Yes, you can pass an array too, which is more lightweight but less "type safe."
    – bobbymcr
    Oct 10, 2009 at 18:08
2

You can use Delegate.BeginInvoke and EndInvoke, to pass any parameters you want

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

Incidentally, with generics, it's useful to define classes such as Doer(Of T1), Doer(Of T1, T2), etc. which have field(s) e.g. V1 As T1, V2 As T2, etc., and theAction As Action(Of T1, T2) etc. and a single method Exec(void), etc. which calls theAction(V1, V2) and a static factory method. This makes it very easy to assemble a MethodInvoker which calls a function with the proper parameters, even in VS2005.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.