一、异步委托开启线程

1
2
3
4
5
6
7
8
9
10
11
public static void Main(string[] args)
{
  Action<int,int> a=add;
  a.BeginInvoke(,,null,null);//前两个是add方法的参数,后两个可以为空
  Console.WriteLine("main()");
  Console.ReadKey();
}
static void add(int a,int b)
{
  Console.WriteLine(a+b);
}

二、通过Thread类开启线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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 = ; i < ; i++)
{
if (i % != )
{
Console.WriteLine("奇数为" + i);
}
}
}
//偶数线程
public static void SetInfo2()
{
for (int i = ; i < ; i++)
{
if (i % == )
{
Console.WriteLine("偶数为" + i);
}
}
}
}

三、通过线程池开启线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    //线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程;
//线程池的作用:
//1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
//2、如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止
public class Program
{
public static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "hjh" });
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
string[] arry = state as string[];//传过来的参数值
int workerThreads = ;
int CompletionPortThreads = ;
ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads);
Console.WriteLine(DateTime.Now.ToString() + "---" + arry[] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads);
}
}

四、通过任务Task开启线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Program
{
public static void Main(string[] args)
{
Task task = new Task(DownLoadFile_My);
task.Start();
Console.ReadKey();
}
static void DownLoadFile_My()
{
Console.WriteLine("开始下载...线程ID:"+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
Console.WriteLine("下载完成!");
}
}
1
2
3
4
5
6
7
8
9
10
new Thread(() =>
{
try
{
//运行的代码
}
catch (Exception ex)
{
}
}).Start();

相关链接(侵删)

  1. C# 开启线程的几种方式

=================我是分割线=================

欢迎到公众号来唠嗑: