新建一个线程(无参数,无返回值)
Thread th = new Thread(PrintName);
th.IsBackground = true; //后台运行
th.Start();
public void PrintName() // 函数
{
//函数体
}
也可使用这样的方法:
Thread th = new Thread(new ThreadStart(PrintName));
th.Start();
这里一定注意Thread中的函数是没有返回值和参数的
那么有一个参数时,就该如下:
string name="name";
Thread th = new Thread(PrintName);
th.IsBackground = true; //后台运行
th.Start(name);
public void PrintName(object name) // 函数
{
//函数体
}
多个参数时,可以定义一个结构体调用,具体如下:
struct Prameters
{
public string p1;
public int p2;
}
Prameters p=new Prameters();
p.p1="name";
p.p2=0;
Thread th = new Thread(PrintName);
th.IsBackground = true; //后台运行
th.Start((object)p);
public void PrintName(object o) // 函数
{
//函数体
Prameters p=(Prameters)o;
}
也可使用这样的方法:
Thread th = new Thread(new ParameterizedThreadStart(PrintName));
th.Start(p);
如果遇到又需要返回值,又需要参数的时候,就可以考虑用异步:
但是需要先申明个委托
public delegate string MethodCaller(string name);//定义个代理
MethodCaller mc = new MethodCaller(GetName);
string name = "my name";//输入参数
IAsyncResult result = mc.BeginInvoke(name,null, null);
string myname = mc.EndInvoke(result);//用于接收返回值
public stringGetName(string name) // 函数
{
return name;
}
这里注意了,通过这种方式生成新线程是运行在后台的(background),优先级为normal
说到这里,不得不提一下C#中串口通信将串口数据传递到窗体控件时,需要用到委托。