zoukankan      html  css  js  c++  java
  • .net多线程传参与接收返回值实现办法

    提起多线程,不得不提起 委托(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); <----带参数和返回值的 线程函数

    新建一个线程(无参数,无返回值)

    1. Thread th = new Thread(new ThreadStart(PrintName)); 
    2.  
    3.  public  void PrintName()    // 函数 
    4.  { 
    5.      //函数体 
    6.  } 

    这里一定注意ThreadStart中的函数是没有返回值和参数的

    那么有参数时,就该如下:

    1. Thread th = new Thread(new ParameterizedThreadStart(PrintName)); 
    2. public  void PrintName(string name)    // 函数
    3. {
    4.  //函数体 
    5. }

     如果遇到又需要返回值,又需要参数的时候,就可以考虑用异步:

    但是需要先申明个委托

    1. public delegate string MethodCaller(string name);//定义个代理 
    2. MethodCaller mc = new MethodCaller(GetName); 
    3. string name = "my name";//输入参数 
    4. IAsyncResult result = mc.BeginInvoke(name,nullnull); 
    5. string myname = mc.EndInvoke(result);//用于接收返回值 
    6.  
    7. public string GetName(string name)    // 函数
    8. {
    9. return name;
    10. }

     这里注意了,通过这种方式生成新线程是运行在后台的(background),优先级为normal

  • 相关阅读:
    怎么快速掌握一门新技术
    Linq相关
    C# 参数按照ASCII码从小到大排序(字典序)
    测试工具
    sql 创建临时表
    sql行合并
    WCF相关
    免费开源分布式系统日志收集框架 Exceptionless
    VPS,虚拟主机,云主机,独立服务器区别
    c# Dictionary的遍历和排序
  • 原文地址:https://www.cnblogs.com/chenjq0717/p/2479541.html
Copyright © 2011-2022 走看看