CSharp 多线程通信

方法:使用C#提供的Action<>和Fun<>泛型委托来处理

需求:开启两个子线程,一个线程负责UDP接收网络数据,另一个线程负责数据的UI界面显示

需求涉及3个线程:

  • UI主线程
  • 界面更新线程
  • UDP接收线程
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
namespace 线程通知演示
{
public partial class Form1 : Form
{
private UdpClient mUdpRecvClient;

public Form1()
{
InitializeComponent();

TextBox.CheckForIllegalCrossThreadCalls = false;

//UI显示线程
Thread showThread = new Thread(show);
showThread.Start();
}

private void show()
{
//泛型委托
Action<string> callback = update;

//UDP接收线程
Thread receiveThread = new Thread(udpReceiver);
receiveThread.IsBackground = true;
receiveThread.Start(callback);
}

private void udpReceiver(Object obj)
{
//获取本地的IP地址
string localIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
localIP = _IPAddress.ToString();
break;
}
}

Console.WriteLine(localIP);

IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse(localIP), 25000); //本机IP和监听端口号

IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);

mUdpRecvClient = new UdpClient(localIpep);

while (true)
{
try
{
byte[] data = mUdpRecvClient.Receive(ref remoteIpep);
string message = Encoding.Default.GetString(data, 0, data.Length);
Console.WriteLine(message);

Action<string> callback = obj as Action<string>;
callback(message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}

private void update(string message)
{
textBox.Text = message;
}
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :