ASP.NET温故而知新学习系列之ASP.NET中的多线程编程—.NET下的多线程编程2.2-Thread中利用构造函数传递参数

 前言

  前一节说了我们创建线程的参数是一个函数,当新的线程启动的时候,它就会执行这个函数,这个函数是没有任何参数的,且没有返回值的,那么新的需求来了,如何调用一个有参数的函数呢?

  利用构造函数传递参数

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

  namespace _2_ThreadArgs
  {
      class Program
      {
          static void Main(string[] args)
          {
              MyCustomClass myclass = new MyCustomClass("我是参数字符串啊");
              Thread thread = new Thread(new ThreadStart(myclass.Worker));
              thread.Start();
              thread.Join(Timeout.Infinite);
          }

      }

     /// <summary>
     /// 我们构造一个类
     /// </summary>
     class MyCustomClass
     {
           private string _args;
           public MyCustomClass(string strArg)
           {
               _args = strArg;
           }

           public void Worker()
           {
               Console.WriteLine("参数输入为:" + _args);  
           } 
     }
  }

  运行机制

  首先我们构造一个类MyCustomClass,这个类是带参数的,且是输入一个字符串,然后通过构造函数保存在一个类成员变量中,另外还有一个Worker()方法是输出一句话。我们先构造一个类,然后把这个类的方法Worker()作为ThreadStart()的参数,就是利用构造函数传递参数。

  运行效果

  

每天学习一点点,每天进步一点点 用文字记录工作,用文字记录人生
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值