8

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

3
  • what does the pfx have to do with the question ...just curious Commented Jul 11, 2011 at 21:51
  • Click this link and search for PFX en.wikipedia.org/wiki/Parallel_Extensions Am I missing something ? thanks Commented Jul 11, 2011 at 21:53
  • nope ...I didn't realize that PFX is comprised of both TPL and PLinq. Commented Jul 11, 2011 at 21:55

2 Answers 2

9

You can do this with a lambda or inline delegate:

myTask = new Task<bool>(() => MyMethod(xyz, abc), _cancelToken); 
Sign up to request clarification or add additional context in comments.

4 Comments

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
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.
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.
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.
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>; } 

1 Comment

Nice to know about tuple. Just read up on this. Upvoted. thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.