我正在构建应用程序,它应该显示每个进程的网络流量。我正在使用 SharpPcap。
想法是开始在新线程上捕获网络流量,每个进程一个线程。它应该如何工作:在新线程上开始捕获,等待 2000 毫秒,停止捕获,在消息框中显示捕获的流量(现在),结束线程.
问题:对于某些进程,消息框显示多次,这意味着该方法被调用的次数超过了应有的次数。我使用列表(我确保列表中的每个进程都是唯一的,那里没有错误)和 foreach 循环。
对于列表中的每个进程,在 foreach 循环中调用方法 StartThreads。
void StartThreads()
{
//filter gets created
IPAddress[] IpAddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string ip = IpAddressList[0].ToString();
string filterReceived = "dst host " + ip + " and " + filter_partReceived;
DownloadForListview procDownload = new DownloadForListview(filterReceived, 2,processIDq,ReturnDevice());
Thread t2 = new Thread(() => procDownload.ReceivedPackets());
t2.IsBackground = true;
t2.Start();
}
}
应该捕获网络流量的线程:
class DownloadForListview
{
private static string FilterDownload;
private static int adapterIndex;
private static int ProcessID;
ICaptureDevice uredaj;
protected static long dataLenght;
protected static double dataPerSec;
public DownloadForListview(string filter, int adapterId,int pid,ICaptureDevice d)
{
uredaj = d;
FilterDownload = filter;
adapterIndex = adapterId;
ProcessID = pid;
}
public void ReceivedPackets()
{
uredaj.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketReceived);
uredaj.Filter = FilterDownload;
uredaj.StartCapture();
Thread.Sleep(2000);
uredaj.StopCapture();
dataPerSec = Math.Round(dataLenght / 2d,3);
MessageBox.Show("Pid:"+ProcessID+"->" + FilterDownload+"->" + dataLenght.ToString());
}
private static void device_OnPacketReceived(object sender, CaptureEventArgs e)
{
dataLenght += e.Packet.Data.Length;
}
}
我还注意到,有时,在调试模式下,我得到了 shappcap 异常:“线程在 00:00:02 后中止”,但我认为这并不重要。