下面是比較早期寫的一個監控UDP接收的線例子:
1 //申明委託
2 public delegate void mydelegate();
3 //添加調用控制的方法
4 public void outtext()
5 {
6 textBox1.Text = Read_str;
7
8 }
9 public void start_server()
10 {
11 while (true)
12 {
13 //接收從遠程主機發送到本地8090連接埠的資料
14 byte[] recData = server.Receive(ref receivePoint);
15 ASCIIEncoding encode = new ASCIIEncoding();
16 //獲得用戶端請求資料
17 Read_str = encode.GetString(recData);
18 //提取用戶端的資訊,存放到定義為temp的字串數組中
19 //string[] temp = Read_str.Split("/".ToCharArray());
20 //線上程中調用對象;
21 mydelegate mydelegate = new mydelegate( outtext );
22 //BeginInvoke/invoke(同步或非同步) 方法來將調用封送到適當的線程
23 textBox1.BeginInvoke(mydelegate, new object[] { });
24
25 }
26 }
27 public void run()
28 {
29 //利用本地8080連接埠號碼來初始化一個UDP網路服務
30 server = new UdpClient(port);
31 receivePoint = new IPEndPoint(new IPAddress(ip), port);
32 //開一個線程
33 startServer = new Thread(new ThreadStart(start_server));
34 //啟動線程
35 startServer.Start();
36
37 }
38 private void Form1_Load(object sender, EventArgs e)
39 {
40 //啟動對時服務
41 run();
42
43 }
參考文章:http://msdn2.microsoft.com/zh-cn/library/757y83z4(VS.80).aspx