What is the standard practice for running a task with multiple parameters

I have now

class MyParamClass { all the parameters I need to pass to the task } MyParamClass myParamObj = new MyParamClass(); myParamObj.FirstParam = xyz; myParamObj.SecondParam = abc; mytask = new Task<bool>(myMethod, myParamObj,_cancelToken); mytask.Start() bool myMethod(object passedMyParamObj) { MyParamClass myParamObj = passedMyParamObj as MyParamClass; //phew! finally access to passed parameters } 

Anyway, can I do this without having to create a MyParamClass class? How can I pass in several parameters for a task without this focus? Is this standard practice? thanks

+8
multithreading c # task-parallel-library task pfx
source share
2 answers

You can do this with a lambda or inline delegate:

 myTask = new Task<bool>(() => MyMethod(xyz, abc), _cancelToken); 
+9
source share

Using a wrapper class for processing is the standard way to do this. The only thing you can do otherwise is to use Tuple to avoid writing MyParamClass .

 mytask = new Task(myMethod, Tuple.Create(xyz, abc), _cancelToken); mytask.Start(); bool myMethod(object passedTuple) { var myParamObj = passTuple as Tuple<int, string>; } 
+5
source share

All Articles