C#多线程函数如何传参数和返回值

提起多线程,不得不提起 委托(delegates)这个概念.

我理解的委托就是 具有 同样参数和返回值 的函数的集合.
比如
public delegate void MyDelegate(int arg);
就是这种形式的函数 void Myfuntion(int i); 的集合.
如何将一个函数加入 委托 的集合?
MyDelegate dele = new MyDelegate(Myfuntion1);
再增加一个
dele += new MyDelegate(Myfuntion2);
...
委托函数 dele 就是 具有整数参数和空返回值的函数 Myfuntion1,2的集合.
调用这个委托函数
dele(1);
就是逐个调用 Myfuntion1,2,...

一般线程函数的声明和启动

Thread t = new Thread(new ThreadStart(MyFunction));
t.Start();
正是调用了没有参数和返回值的 委托函数 ThreadStart
其中的参数MyFunction 是 这个委托函数中的一员.

很明显 这样无法传参数和返回值,那我们该怎么办?

答案就在委托 的BeginInvoke() 方法上, BeginInvoke() 也是(异步)启动一个新线程.
例如
MyDelegate dele = new MyDelegate (MyFunction);
dele.BeginInvoke(10,"abcd");
void MyFunction(int count, string str);
可以实现参数的传递.

 

如何收集线程函数 的 返回值?


BeginInvoke 对应 有个 EndInvoke 方法,而且运行完毕返回 IAsyncResult 类型的返回值.
这样我们可以这样收集 线程函数的 返回值

MyDelegate dele = new MyDelegate (MyFunction);
IAsyncResult ref = dele.BeginInvoke(10,"abcd");
....
int result = dele.EndInvoke(ref); <----收集 返回值
int MyFunction(int count, string str); <----带参数和返回值的 线程函数

 

转载于:https://www.cnblogs.com/doubaokun/archive/2008/11/27/1341915.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值