线程方法定义:
- public void ThreadDo (string param,int n){
- //函数体实现处理方法
- }
复制代码 ★匿名线程方法调用:
//匿名线程,Labmda表达式进行多参数函数传参
- Thread thread = new Thread(() => ThreadDo("param1",1));
- thread.IsBackground = true;
- thread.CheckIllegalCrossCtotorl = false;
- thread.Start();
复制代码 ★总体概括介绍线程使用大体三种主流方法:
①这三种方法分别是:
1. 写一个类型,在构造函数中传参,而后在类型中写无参数函数,里面使用内部变量,从而达到传参的目的。
2. 使用lambda方法,通过直接调用已有的带参数函数,通过lambda表达式向线程传参。
3. 使用thread.start(object parameter)的方法。
第一种方式:
//通过ThreadStart委托告诉子线程执行什么方法
- ThreadStart threadStart = new ThreadStart(函数名);
- Thread thread = new Thread(threadStart);
- thread.Start();
复制代码 ②C#如何在子线程中显示编辑控件内容,由于第一种线程调用无法传入参数所以在此利用委托Delegate给第一种线程调用传入参数
- delegate void add(string text);
- //开启委托
- public void Test(){
- BeginInvoke(new add(Method), “待传入Method函数的参数”);
- }
- public void Method(string input){
- //编辑框对象 textBox1
- textBox1.Text = input;
- }
复制代码
二、按钮函数开启线程,在子线程中显示编辑框信息
- private void OpenImage_Click(object sender, EventArgs e) {
- Thread thread = new Thread(new ThreadStart(Test));
- thread.Start()
- }
复制代码 ③用 ParameterizedThreadStart 委托实现:
ParameterizedThreadStart委托与ThreadStart委托非常相似,但ParameterizedThreadStart委托是面向带参数方法的。
- namespace ThreadApply{
- public class Person
- {
- public string Name
- {
- get;
- set;
- }
- public int Age
- {
- get;
- set;
- }
- }
- public class Message
- {
- public void ShowMessage(object person)
- {
- if (person != null)
- {
- Person _person = (Person)person;
- string message = string.Format("\n{0}'s age is {1}!\nAsync threadId is:{2}",
- _person.Name, _person.Age, Thread.CurrentThread.ManagedThreadId);
- Console.WriteLine(message);
- }
- for (int n = 0; n < 10; n++)
- {
- Thread.Sleep(300);
- Console.WriteLine("The number is:" + n.ToString());
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Main threadId is:" + Thread.CurrentThread.ManagedThreadId);
- Message message = new Message();
- //绑定带参数的异步方法
- Thread thread = new Thread(new ParameterizedThreadStart(message.ShowMessage));
- Person person = new Person();
- person.Name = "Jack";
- person.Age = 21;
- thread.Start(person); //启动异步线程
- }
- }}
复制代码 详情请参考我的博客:https://blog.csdn.net/weixin_50016546/article/details/123954254
|