我正在构建应用程序,它应该显示每个进程的网络流量。我使用SharpPcap。
想法是开始捕获新线程上的网络流量,每个进程一个线程。它应该如何工作:在新线程上开始捕获,等待2000毫秒,停止捕获,在消息框中显示捕获的流量(现在) ,结束线程。
问题:对于某些进程,消息框被多次显示,这意味着该方法被调用的次数超过它应该的次数。我使用list(我确保列表中的每个进程都是唯一的,没有错误那里)和foreach循环。
方法StartThreads在foreach循环中为列表中的每个进程调用。
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;
}
}
我也注意到有时候,在调试模式下,我得到了锐镜异常:“线程在00:00:02之后被中止了”但我不认为这很重要。
答案 0 :(得分:1)
从DownloadForListView中创建的所有变量中删除'static'关键字解决了这个问题。
所有线程都访问相同的变量,而不是为每个线程创建新的局部变量。