首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

多執行緒在 Visual C# 網路程式設計中的應用(三):單執行緒掃描器實作與效能基準

     編輯:關於C語言

Form1.cs 命名空間引入


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net.Sockets;
using System.Net;

button1_Click:循序掃描邏輯


private void button1_Click(object sender, EventArgs e)
{
    listBox1.Items.Clear();
    DateTime startTime = DateTime.Now;

    string ipPrefix = $"{numericUpDown1.Value}.{numericUpDown2.Value}.{numericUpDown3.Value}.";
    int min = (int)numericUpDown4.Value;
    int max = (int)numericUpDown5.Value;

    if (min > max) { MessageBox.Show("IP 區間不合法!"); return; }

    progressBar1.Minimum = min;
    progressBar1.Maximum = max;

    for (int i = min; i <= max; i++)
    {
        string ip = ipPrefix + i;
        IPAddress addr = IPAddress.Parse(ip);
        try
        {
            IPHostEntry host = Dns.GetHostEntry(addr);
            listBox1.Items.Add($"{ip} 名稱為:{host.HostName}");
        }
        catch
        {
            listBox1.Items.Add($"{ip} 主機沒有響應!");
        }
        progressBar1.Value = i;
    }

    TimeSpan elapsed = DateTime.Now - startTime;
    label4.Text = elapsed.Seconds + " 秒";
    MessageBox.Show("掃描完成!");
    progressBar1.Value = min;
}

時間處理關鍵點

  • DateTime.Now 取得本地時間
  • TimeSpan 相減得差值:end - start
  • elapsed.Seconds 只取秒數部分;完整格式建議 elapsed.TotalSeconds 或 elapsed.ToString()

執行結果與效能基準

掃描 10.138.198.1 ~ 10 (10 個 IP):**43 秒**

單執行緒掃描執行畫面

圖 02:單執行緒掃描網路電腦 - 執行介面

效能瓶頸分析

  • Dns.GetHostEntry 為同步阻塞呼叫,內含 DNS 查詢、逆向解析、網路往返
  • 單執行緒循序執行,總耗時 ≈ Σ(單次解析耗時)
  • 若掃描 254 個 IP (C 類網段),預估耗時 **15~20 分鐘** — 完全不可接受

下一篇將展示如何引入多執行緒將耗時壓縮至個位數秒。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved