C# 多参数线程以及匿名函数

今天早上的时候,要写一个多参数的线程,找到一种,用新建一个对象的方法来参数,其实传入的也是单个参数,只不过传入的是一个对象,只不过对象里有很多属性罢了。后来在stackoverflow上看到这么个答案,觉得很赞。所以写下来,以备不时之需。

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  t.Start();
  return t;
}

private static void RealStart(SomeType param1, SomeOtherType param2) {
  ...
}

其用了一个匿名函数。

要理解上面的代码,首先看要看Thread()这个类的析构函数:

   
        public Thread(ParameterizedThreadStart start); 
        public Thread(ThreadStart start);      
        public Thread(ParameterizedThreadStart start, int maxStackSize);   
        public Thread(ThreadStart start, int maxStackSize);
你会发觉ThreadStart和ParmeterizeThreadStart 两个都是delegate,也就是委托函数。对于委托函数从.net3.0开始,有个很好的替代就是匿名函数。在MSDN的官方网站中找到了 委托函数的发展过程,最后转换为匿名函数,不可谓不精彩,更加简单实用。

 TestDelegate testDelA = new TestDelegate(M);

// C# 2.0: A delegate can be initialized with
// inline code, called an "anonymous method." This
// method takes a string as an input parameter.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

// C# 3.0. A delegate can be initialized with
// a lambda expression. The lambda also takes a string
// as an input parameter (x). The type of x is inferred by the compiler.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };

// Invoke the delegates.
testDelA("Hello. My name is M and I write lines.");
testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");

A老老实实的教科书,就相当于开头所说的那样,新建一个对象,对象属性传参数;B跟A同理,但是B可以传多个参数了,差不多就是C的雏形了;C的话更加简洁,直接一个Lambda表达式匿名函数就委托了。

       写到这,大致就明白了,其实就是用了一个匿名函数()=>RealStart(param1 ,param2)替代了delegate ParameterizedThreadStart(object obj)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值