C#线程传递参数的方式
前言:线程间参数的传递经常用到,本文介绍线程间传递参数常用的几种方式:
方式一:使用ParameterizedThreadStart委托
示例如下:
using System; using System.Threading; namespace ConsoleLearn { class Program { static void Main(string[] args) { Thread thread = new Thread(new ParameterizedThreadStart(SayHello)); thread.Start("zhangsan"); //简写 //Thread thread = new Thread(SayHello); //thread.Start("zhangsan"); Console.ReadKey(); } public static void SayHello(object name) { if (!string.IsNullOrEmpty(name as string)) { Console.WriteLine($"Hello! {name}"); } } } }
查看ParameterizedThreadStart底层如下:
public delegate void ParameterizedThreadStart(object? obj);
可以看出ParameterizedThreadStart是底层自定义的一个只有一个object参数,无返回值的委托,所以传递方法的时候需要一个只有一个object参数,且返回类型为void的方法(委托实质就是同一种类型方法的抽象)
方法二:定义自定义类:
示例如下:
using System; using System.Threading; namespace ConsoleLearn { public class MyThread { private string name; public MyThread(string name) { this.name = name; } public void SayHello() { Console.WriteLine($"Hello{name}"); } } class Program { static void Main(string[] args) { //Thread thread = new Thread(new ParameterizedThreadStart(SayHello)); //thread.Start("zhangsan"); //简写 //Thread thread = new Thread(SayHello); //thread.Start("zhangsan"); MyThread myThread = new MyThread("zhangsan"); Thread thread = new Thread(myThread.SayHello); thread.Start(); Console.ReadKey(); } public static void SayHello(object name) { if (!string.IsNullOrEmpty(name as string)) { Console.WriteLine($"Hello! {name}"); } } } }
可以看出,实质就是将参数封装在一个类中,实例化的时候将参数传递进去
方式三:Lambda表达式:
示例如下:
using System; using System.Threading; namespace ConsoleLearn { public class MyThread { private string name; public MyThread(string name) { this.name = name; } public void SayHello() { Console.WriteLine($"Hello{name}"); } } class Program { static void Main(string[] args) { //Thread thread = new Thread(new ParameterizedThreadStart(SayHello)); //thread.Start("zhangsan"); //简写 //Thread thread = new Thread(SayHello); //thread.Start("zhangsan"); //MyThread myThread = new MyThread("zhangsan"); //Thread thread = new Thread(myThread.SayHello); //thread.Start(); Thread thread = new Thread(()=>SayHello("zhangsan")); thread.Start(); Console.ReadKey(); } //public static void SayHello(object name) //{ // if (!string.IsNullOrEmpty(name as string)) // { // Console.WriteLine($"Hello! {name}"); // } //} public static void SayHello(string name) { if (!string.IsNullOrEmpty(name as string)) { Console.WriteLine($"Hello! {name}"); } } } }
以上就是线程间传递参数的三种方式,若有其他方式,欢迎补充交流,3Q~
不积跬步,无以至千里;不积小流,无以成江海。ヾ(◍°∇°◍)ノ゙