(12条消息) C#中关于线程启动运行带多参数方法的操作
不带参数的用ThreadStart委托指向要执行的方法,将ThreadStart对象传入Thread的构造函数
public void Test()
{
Console.WriteLine("Test");
}
ThreadStart s = new ThreadStart(Test);
Thread th = new Thread(s);
th.Start();
带参数的可以用ParmeterizedThreadStart委托
ParameterizedThreadStart s = new ParameterizedThreadStart(TestThreadParsms);
Thread t = new Thread(s);
t.IsBackground = true;
t.Start("你好啊");
public void TestThreadParsms(object obj)
{
Console.WriteLine(obj.ToString());
}
如果遇到要传入多个参数的方法的时候,可以有2中解决方式,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace C1
{
class Program
{
static void Main(string[] args)
{
#region 利用ParameterizedThreadStart委托传入object数组,将参数放到数据中传入线程
//ParameterizedThreadStart s = new ParameterizedThreadStart(Test1);
//Thread t = new Thread(s);
//t.IsBackground = true;
//t.Start(new object[]{"你好啊",2});
#endregion
#region 利用新建类中写实现目的功能的方法,转换成利用ThreadStart委托
MyClass my = new MyClass("你好啊", 2);
ThreadStart s = new ThreadStart(my.Test1);
Thread t = new Thread(s);
t.Start();
#endregion
Console.ReadKey();
}
public static void Test1(object obj)
{
Console.WriteLine(((object[])obj)[0].ToString());
Console.WriteLine((Convert.ToInt32(((object[])obj)[1])*32).ToString());
}
}
class MyClass
{
private string str;
public string Str
{
get { return str; }
set { str = value; }
}
private int num;
public int Num
{
get { return num; }
set { num = value; }
}
public MyClass(string str,int num)
{
this.str = str;
this.num = num;
}
public void Test1()
{
Console.WriteLine(this.str);
Console.WriteLine((this.num*32).ToString());
}
}
}
赞 (0)