线程上调用带参函数

线程传参步骤: 
1、通过实例化委托时来调用工作函数, 
                       工作函数是带参数的;委托也带参数由下面的步骤来传参数 
2、通过实例化线程时候调用一个方法,该方法的作用将参数传给委托 


实例如下: 
using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading ; 
namespace _03_ThreadDelegate 

    public class SimpleThread 
    { 
        //委托变量声明 
        public delegate void delegateStart(object o); 
        //一个class 
        public class Args 
        { 
            public object o; 
            public delegateStart delegateOne; 
            public void delegateWork()  //将参数传到委托上 
            { 
                delegateOne (o); 
            } 
        } 
        //创建线程方法 
        public static Thread CreateThread(delegateStart delegatestart,object arg) 
        { 
            Args args = new Args(); 
            args.o = arg; 
            args.delegateOne = delegatestart; 
            Thread t = new Thread(new ThreadStart(args.delegateWork)); 
            return t; 
        } 
    } 
    class Worker 
    { 
        public static void WorkMathod(object o) 
        { 
            Console.WriteLine("参数为:" + o); 
        } 
    } 
    class Program 
    { 
        public SimpleThread.delegateStart delegateOne; 
        static void Main(string[] args) 
        { 
            //Thread t = SimpleThread.CreateThread(new SimpleThread.delegateStart(Worker.WorkMathod), "-----我是参数!"); 
            //t.Start(); 
            //t.Join(); 
            //等价于一下代码: 
            SimpleThread.Args  Simple_args = new SimpleThread.Args (); 
            Simple_args.o = "1"; 
            Simple_args.delegateOne = new SimpleThread.delegateStart(Worker.WorkMathod );//实例化委托,委托中再调用工作函数,来完成工作函数的运行! 
            Thread t=new Thread (new ThreadStart(Simple_args.delegateWork  ));//调用线程,线程上运行一个方法,该方法将参数传进委托方法中 
            t.Start(); 
            t.Join(); 
             delegateOne("哈哈"); 
            Thread t = new Thread(new ThreadStart()); 
            t.Start(); 
            t.Join(); 
        } 
    } 
}

转载于:https://www.cnblogs.com/zhiji6/archive/2009/01/06/1649371.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值