方法一:Thread
首先创建一个控制台应用程序,接着创建一个有参数的方法便于线程传递。注意参数的类型必须为Object
static void DownloadFile(object obj)
{
Console.WriteLine("开始");
Thread.Sleep(200);
Console.WriteLine("结束"+obj);
}
接着我们在主函数中调用
Thread t = new Thread(DownloadFile);//方法需要在这里调用
t.Start("你好");
当然上面两行代码我们也可以用下面的表达式来表示
Thread t = new Thread(() =>
{
Console.WriteLine("开始");
Thread.Sleep(200);
Console.WriteLine("结束"+Thread .CurrentThread.ManagedThreadId );
});
t.Start();
如果是想从另一个类中的构造方法传递值或方法,那就先添加一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace xianCheng
{
class MyThread
{
private string name;
private int id;
public MyThread(string name,int id)
{
this.name = name;
this.id = id;
Console.WriteLine("构造方法");
}
public void text1()
{
Console.WriteLine("text1 "+name+"---" +id);
}
}
}
接着在主类的主方法中调用
MyThread my = new MyThread("c", 1);
Thread t1 = new Thread(my.text1);//方法必须在Tread的括号里调用而不是在Start
t1.Start();
方法二:Task
这个方法几乎与Thread类似,但需要加头文件using System.Threading.Tasks;
方法三:采用任务工厂TaskFactory
TaskFactory tf = new TaskFactory();
Task t1 = tf.StartNew(ThreadMethod);//括号中是线程的方法
Task t2 = tf.StartNew(ThreadMethod);
这个创建后可以调用多个线程比较方便