使用Thread类 开启线程例子
例子1
static void Main(string[] args)
{
//第一种方式
Thread t = new Thread(DownLoadFile);
t.Start();
Console.WriteLine("Main");
Console.ReadKey();
}
static void DownLoadFile()
{
Console.WriteLine("开始下载: "+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("下载完成");
}
例子2 使用lambda表达式 任何使用委托的地方都可以使用lambda表达式
static void Main(string[] args)
{
Thread t = new Thread(() =>
{
Console.WriteLine("开始下载: " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("下载完成");
});
t.Start();
Console.WriteLine("Main");
Console.ReadKey();
}
例子3
class Program
{
static void Main(string[] args)
{
MyThread my = new MyThread("xx.bt", "bbs");
Thread p = new Thread(my.DownFile);
p.Start();
Console.WriteLine("Main");
Console.ReadKey();
}
}
public class MyThread
{
private string fileName;
private string filePath;
public MyThread(string fileName,string filePath)
{
this.fileName = fileName;
this.fileName = filePath;
}
public void DownFile()//string fileName,string filePath
{
Console.WriteLine("开始下载: " + Thread.CurrentThread.ManagedThreadId + " File name: " + fileName);
Thread.Sleep(2000);
Console.WriteLine("下载完成");
}
}