c#线程问题(1)

delegate
public delegate void ParameterizedThreadStart(Object obj)
public delegate void ThreadStart()

MSDN:在创建托管的线程时,在该线程上执行的方法将通过一个传递给 Thread 构造函数的 ThreadStart 委托或 ParameterizedThreadStart 委托来表示。 在调用 Thread. Start 方法之前,该线程不会开始执行。执行将从 ThreadStartParameterizedThreadStart 委托表示的方法的第一行开始。

Visual Basic 和 C# 用户在创建线程时可以省略 ThreadStartParameterizedThreadStart 委托构造函数。 在 Visual Basic 中,将方法传递给 Thread 构造函数时使用 AddressOf 运算符,例如 Dim t As New Thread(AddressOf ThreadProc) 在 C# 中,只需指定线程过程的名称。 编译器会选择正确的委托构造函数。

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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            UPPER = 100;
            //无参数使用   ThreadStart委托
            Thread thread1 = new Thread(new ThreadStart(sop));
            thread1.Start();
            //有参数使用   ParameterizedThreadStart委托
            //如果有参数,参数类型必须是Object类型,否则抛出异常
            Thread thread2 = new Thread(new ParameterizedThreadStart(sops));
            thread2.Start("myData");


            //同时也可以不写委托
            Thread thread3=new Thread(sop);
            thread3.Start();
            Thread thread4=new Thread(sops);
            thread4.Start("不调用委托也可以传值");
            Console.ReadLine();


        }

        static  void sop() 
        {
            for (int i = 0; i < UPPER; i++)
            {
                Console.WriteLine("hello this is thread(sop)------------"+i); 
            }
         
        }

        static void sops(object data)
        {
            for (int i = 0; i < UPPER; i++)
            {
                Console.WriteLine("hello this data is {0}++++++++++++++++{1}", data.ToString(),i);
            }
        }

        public static int UPPER { get; set; }
    }
}
原文地址:https://www.cnblogs.com/anbylau2130/p/3183374.html