最近用到了控制台程序,还要能中途停下来并保存参数,就需要开启一个线程来检查是否需要退出程序,总结一下实现多线程的几种方式
第一种,也是最常用的通过Thread类开启线程
lamda表达式方式实现,这种方式可以直接放到函数里执行,非常方便,也不需要将函数使用static进行修饰
Thread t = new Thread(() =>
{
Console.WriteLine("开始下载" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("下载完成");
});
t.Start();
常用写法
public class Program
{
public static void Main(string[] args)
{
Thread t1;
Thread t2;
t1 = new Thread(SetInfo1);
t2 = new Thread(SetInfo2);
t1.Start();
//线程睡眠
//t1.Join(1000);
//挂起线程
t1.Suspend();
//继续执行线程
t1.Resume();
//结束线程
//t1.Abort();
t2.Start();
Console.ReadKey();
}
//奇数线程
public static void SetInfo1()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 != 0)
{
Console.WriteLine("奇数为" + i);
}
}
}
//偶数线程
public static void SetInfo2()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
Console.WriteLine("偶数为" + i);
}
}
}
}
第二种,最近流行起来的通过Task
public class Program
{
public static void Main(string[] args)
{
Task task = new Task(DownLoadFile);
task.Start();
Console.ReadKey();
}
static void DownLoadFile()
{
Console.WriteLine($"开始下载,线程ID:{Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(500);
Console.WriteLine("下载完成!");
}
}
第三种,通过线程池开启线程
public class Program
{
public static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "test" });
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
string[] arry = state as string[];//传过来的参数值
int workerThreads = 0;
int CompletionPortThreads = 0;
ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads);
Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads);
}
}
第四种,异步委托开启线程,在项目中我没有用过这种方法
public class Program
{
public static void Main(string[] args)
{
Action<int, int> a = add;
a.BeginInvoke(3, 4, null, null);
Console.WriteLine("执行线程");
Console.ReadKey();
}
static void add(int a, int b)
{
Console.WriteLine(a + b);
}
}