public static class Sample01 { public static void Send(IPAddress address, int port) { var tcp = new TcpClient(); try { //C10K,10K个客户端,4G,10M,上 tcp.Connect(address, port); tcp.GetStream().Write(Encoding.ASCII.GetBytes("Hello")); } catch (Exception e) { Console.WriteLine(e); throw; } finally { tcp.Close(); } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
第二阶段
基于回调的异步操作
public static class Sample02 { public static void Send(IPAddress address, int port) { var client = new TcpClient(); // 开始异步连接 client.BeginConnect(address, port, ar => { // 无论成功失败都会调用这个回调 try { client.EndConnect(ar); } catch (Exception e) { Console.WriteLine(e); client.Close(); } var bytes = Encoding.ASCII.GetBytes("Hello"); var stream = client.GetStream(); stream.BeginWrite(bytes, 0, bytes.Length, result => { try { stream.EndWrite(result); } catch (Exception e) { Console.WriteLine(e); } finally { client.Close(); } },null); },null); } }
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
第三阶段
Task TPL 任务并行库分离了异步操作与注册回调的处理,async和await
第一种,任务中执行指定的委托(运行时内部的线程池中运行),Run和Factory.StartNew
public class TplSample { public static Task SendAsync(IPAddress address, int port) { var client = new TcpClient(); // 异步连接 var task = client.ConnectAsync(address, port); var a = new TaskFactory(); // 异步发送数据 var task1 = task.ContinueWith(t => { var bytes = Encoding.ASCII.GetBytes("Hello"); var stream = client.GetStream(); // 返回一个新的task // 这里会产生Task嵌套 // 在外部使用Unwrap方法解包 return stream.WriteAsync(bytes, 0, bytes.Length); }).Unwrap(); // 异步处理发送结果 var task2 = task1.ContinueWith(t => { if (t.IsFaulted) { // 失败 } else if (t.IsCompleted) { // 完成 } client.Close(); }); return task2; } public static void Run(IPAddress address, int port) { // 创建1万个Task var tasks = new Task[10000]; for (var i = 0; i < tasks.Length; i++) { // SendAsync 本身就是一个异步方法 tasks[i] = SendAsync(address, port); } // 等待所有异步操作执行完成 Task.WaitAll(tasks); } }
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
45
46
47
48
49
50
51
第二种,承诺对象,Promise,将来对象,Future
public class PromiseSample { public static Task ConnectAsync(TcpClient client,IPAddress address, int port) { // 创建一个承诺对象, var promise = new TaskCompletionSource