开发者

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

开发者 https://www.devze.com 2023-03-19 18:24 出处:网络
Right now I have class MyParamClass { all the parameters I need to pass to the task }开发者_开发问答

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


You can do this with a lambda or inline delegate:

myTask = new Task<bool>(() => MyMethod(xyz, abc), _cancelToken);


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号