2013-10-02 29 views
1

返工一个老问题:传递方法名称和参数动态地thread.Start

我有我的简化穿了很多的方法,但是我传递多个参数它有问题!

public static Thread StartThread(ParameterizedThreadStart targetMethod, object argument) 
{ 
      Thread result = null; 

      result = new Thread(targetMethod); 

      result.Start(argument); 
      return result; 
} 

有没有什么办法可以将多个参数传给result.Start(argument)?或者还有其他方法可以做到这一点,同时保持可扩展性?

任何帮助将是真棒:)

谢谢〜丹尼尔

回答

2

这很简单

static void targetMethod(object obj) 
{ 
    Tuple<string, int> tuple = (Tuple<string, int>)obj; 
    Console.WriteLine(tuple.Item1); 
    Console.WriteLine(tuple.Item2); 
} 

static void Main(string[] args) 
{ 
    Thread thread = new Thread(targetMethod); 
    thread.Start(new Tuple<string, int>("simple string", 123)); 
    thread.Join(); 
    Console.ReadLine(); 
} 
1

您可以传递对象参数Tuple对象StartThread方法。另一个首选的方式可能是传递一些classinterface的对象而不是Tuple。包含元组返回到元组在targetMethod

object population = new Tuple<string, int>("a", 1); 

类型铸造对象。

private void targetMethod(object t) 
{ 
    Tuple<string, int> t = (Tuple<string, int>)population; 
    string yourStringVariable = t.Item1; 
    int yourIntVariable = t.Item2; 
} 
+0

在这一点上,将对象强制转换为接口而不是元组?通过这种方式,我可以将参数写成=>表达式 – Burdock

+0

您可以将任何对象传递给接口,您需要使用Func来使用表达式IMO – Adil

+0

运行速度会更快?这种方法被称为相当多的,所以这是值得我优化这段代码的运行时间。 – Burdock