线程5:委托开启线程

使用委托开启一个线程,参数传递,以及获取线程的返回数值。

例子:

Action ac = ThreadMethod1;

ac.BeginInvoke(null,null);

 

注意;

委托开启的线程都是后台线程,后台线程会随着前台线程的关闭而自动关闭

 

源代码:

/***
 *学习使用委托开启线程 
 * 
 * 注意;
 * 委托开启的线程都是后台线程,后台线程会随着前台线程的关闭而自动关闭


 * 
 * 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


namespace 委托开启线程
{
    class Program
    {
        /// <summary>
        /// 委托开启线程,不带参数
        /// </summary>
        public void Test1()
        { 
            Action ac = Thread1;
            ac.BeginInvoke(null, null);
            //Console.ReadLine();
        }


        public void Thread1()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("线程1");
            }
        }


        /// <summary>
        /// 委托开启线程,带一个参数
        /// </summary>
        public void Test2()
        {
            Action<int> ac = Thread2;
            ac.BeginInvoke(22, null, null);
            Console.ReadLine();


        }
        public void Thread2(int num)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("线程2 + 参数" + num);
            }
        }


        /// <summary>
        /// 委托开启线程,带两个参数
        /// </summary>
        public void Test3()
        {
            Action<int,int> ac = Thread3;
            ac.BeginInvoke(22, 33, null, null);
            Console.ReadLine();


        }
        public void Thread3(int num1, int num2 )
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("线程2 + 参数" + num1 +  num2);
            }
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            //obj.Test1();
            obj.Test2();
           // Console.ReadKey();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值