其他分享
首页 > 其他分享> > 1.9 向线程传递参数

1.9 向线程传递参数

作者:互联网

1. 如何提供一段代码来使用要求的数据运行另一个线程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Console;
using static System.Threading.Thread;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var sample = new ThreadSample(10);

            var threadOne = new Thread(sample.CountNumbers);
            threadOne.Name = "ThreadOne";
            threadOne.Start();
            threadOne.Join();

            WriteLine("------------------------------------");

            
            var threadTwo = new Thread(Count);
            threadTwo.Name = "ThreadTwo";
            threadTwo.Start(8);
            threadTwo.Join();

            WriteLine("------------------------------------");

            
            var threadThree = new Thread(() => CountNumbers(12));
            threadThree.Name = "ThreadThree";
            threadThree.Start();
            threadThree.Join();
            WriteLine("------------------------------------");

            int i = 10;
            var threaFour = new Thread(() => PrintNumber(i));
            i = 20;
            var threadFive = new Thread(() => PrintNumber(i));
            threaFour.Start();
            threadFive.Start();
        }
        static void Count(Object iterations)
        {
            CountNumbers((int)iterations);

        }

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

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

        class ThreadSample
        {
            private readonly int _iterations;
            public ThreadSample(int iterations)
            {
                _iterations = iterations;
            }
            public void CountNumbers()
            {
                for (int i = 0; i < _iterations; i++)
                {
                    Sleep(TimeSpan.FromSeconds(0.5));
                    WriteLine($"{CurrentThread.Name} prints {i}");
                }
            }
        }
    }
}

 2. 使用Lambda表达式引用另一个C#对象的方式被称为闭包。当在lambda表达式中使用任何局部变量时,C#会生成一个类,并将该变量作为该类的一个属性。所以实际上该方式与threadOne线程中使用的一样,但是我们无须定义该类,C#编译器会自动帮我们实现。这可能会导致几个问题。例如,如果在多个lambda表达式中使用相同的变量,他们会共享该变量的值。在前一个例子中演示了这种情况。当启动threadFour和threadFive线程时,它们都会打印20,因为在这两个线程启动之前变量被修改为20. 

标签:Thread,int,System,1.9,static,参数,iterations,using,线程
来源: https://www.cnblogs.com/cherry1022/p/16558621.html