1.9 向线程传递参数

  • 《C#多线程编程实战》1.9节笔记
  • 演示如何提供一段代码来使用要求的数据运行另一个线程。代码介绍了4种方式来满足此任务。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var sample = new ThreadSample(10);//【方式1】用构造函数传递值
            var threadOne = new Thread(sample.CountNumbers);
            threadOne.Name = "threadOne";
            threadOne.Start();
            threadOne.Join();
            Console.WriteLine("--------");

            var threadTwo = new Thread(Count);
            threadTwo.Name = "thread2";
            threadTwo.Start(8);//【方式2】用start传递值
            threadTwo.Join();
            Console.WriteLine("--------");

            var threadThree = new Thread(()=>CountNumbers(12));//【方式3】用lambda表达式传递值
            threadThree.Name = "thread3";
            threadThree.Start();
            threadThree.Join();
            Console.WriteLine("-------");
            int i = 20;
            var threadFour = new Thread(()=>PrintNumber(i));//输出结果:0
            i = 0;
            var threadFive = new Thread(()=>PrintNumber(i));//输出结果:0
            threadFour.Start();//【方式4】在多个lambda表达式中使用相同变量,他们会共享该变量值,都threadFour、threadFive都输出0因为这两个线程启动前被改为了0
            threadFive.Start();
            Console.ReadLine();

        }

        static void Count(object interations)
        {
            CountNumbers((int )interations);
        }

        static void CountNumbers(int iterations)
        {
            for (int i = 0; i <= iterations; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}",Thread.CurrentThread.Name,i);

            }
        }

        static void PrintNumber(int number)
        {
            Console.WriteLine(number);
        }

        class ThreadSample
        {
            private readonly int _iterations;

            public ThreadSample(int iterations)
            {
                _iterations = iterations;
            }

            public void CountNumbers()
            {
                for (int i = 0; i < _iterations; i++)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                    Console.WriteLine("{0} prints {1}",Thread.CurrentThread.Name,i);
                }
            }
                 
        }
    }
}


原文地址:https://www.cnblogs.com/anjun-xy/p/11746733.html