开发者

How can I convert datatype for argument passed into Thread in C#

I have a MyFunction that may take several datatypes, which are all very similar. I just want to 开发者_高级运维pass all these different types of data into MyFunction with multithreading and type cast in MyFunction. Is this something possible? Is using dictionary a good idea? Please advise.

Main(){
    Parallel.ForEach(objectType1, MyFunction)
    Parallel.ForEach(objectType2, MyFunction)
    Parallel.ForEach(objectType3, MyFunction)
}

MyFunction(object arg){
  Dictionary<string, object> d = (Dictionary<string, object>) arg;
  Type1 t1;
  Type2 t2;
  Type3 t3;
  if (d.Key == "Type1") {
        t1 = (Type1) d.Value;
        ProcessType1(t1);
  }
  else if (d.Key == "Type2") {
    t2 = (Type2) d.Value;
        ProcessType2(t2);
  }
  else if (d.Key == "Type3") {
    t3 = (Type3) d.Value;    
        ProcessType3(t3);
  }

}


You could do:

MyFunction (object arg) {
    if (arg is Type1) { ProcessType1(arg as Type1); }

    else if (arg is Type2) { ProcessType2(arg as Type2); }

    else if (arg is Type3) { ProcessType3(arg as Type3); }
}


If (object is type)
{
var type1 = object as type
//Process
}

Not sure why anything else would be required.

You could also use a strategy pattern and send in IStrategy concrete class.


You could use a generic method. Perhaps like this:

    private void MyFunction<T>(T arg)
    {

    }

You could possibly even cut down on the number of void ProcessTypeX(object arg) methods that you have by making it generic and handling it all in one method call. That would I suppose depend on the complexity of the methods themselves.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜