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

来源:互联网 发布:淘宝店铺卖了有风险吗 编辑:程序博客网 时间:2024/06/04 19:59
 前言

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

  利用构造函数传递参数

  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()的参数,就是利用构造函数传递参数。

  运行效果

  

每天学习一点点,每天进步一点点 用文字记录工作,用文字记录人生
原创粉丝点击