9

Right now I have

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
}

Is there anyway I can do this without having the need to create class MyParamClass ? How can I pass multiple params to a task without this jugglery ? Is this the standard practice ? thank you

Gullu
  • 3,477
  • 7
  • 43
  • 70

2 Answers2

9

You can do this with a lambda or inline delegate:

myTask = new Task<bool>(() => MyMethod(xyz, abc), _cancelToken);
Andy Lowry
  • 1,767
  • 13
  • 12
  • that is much cleaner. I guess when I have a large number of params I will go with what I have and for a smaller list I will use your approach for readability. thanks – Gullu Jul 11 '11 at 22:10
  • If your finding you have a lot of parameters I tend to try to refactor all the code for the task into another class as well, pass the params through the constructor or Properties and then have a DoWhateverAsync() that returns the Task. Not always that easy to do, but usually worth a try. – Andy Lowry Jul 11 '11 at 22:19
  • 1
    This approach is easy to read, and it's convenient since it essentially is getting the compiler to build the param class for you behind the scenes. Just be careful you don't get in trouble with access to modified closures, which is a risk your original approach didn't have. – Scott Pedersen Jul 11 '11 at 22:21
  • Thanks Scott. "access to modified closures" was somethimg I had seen via Resharper before but not really understood. I see many articles online explaining this. Time for more coffee and reading. – Gullu Jul 11 '11 at 22:34
6

Using a wrapper class to handle is the standard way to do this. The only thing you can do otherwise is use a 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>;
}
Guvante
  • 18,775
  • 1
  • 33
  • 64