1

我正在使用 pcap.net 来捕获数据包。捕获数据包的方法正在新线程中运行。当我想停止/恢复捕获时,我使用 ManualResetEvent 来停止/恢复线程。

它工作正常,问题是当我中断捕获并重新启动它(停止并恢复线程) - 通信器接收到在线程停止期间到来的数据包。我认为这是因为通信器的缓冲区。

是希望通信器在线程停止时不获取数据包,并在线程恢复时再次获取数据包。有什么帮助吗?

我的代码:

    #region Members
    private PacketCommunicator _Communicator;
    private IList<LivePacketDevice> _allDevices;
    private PacketDevice selectedDevice;
    private Thread captureThread;
    private ManualResetEvent _pauseEvent = new ManualResetEvent(true);

    #endregion

    #region Methods

    public PacketGateway()
    {
        try
        {
            _allDevices = LivePacketDevice.AllLocalMachine;
            selectedDevice = _allDevices[0];
            captureThread = new Thread(StartListening);
        }
        catch (Exception e)
        {
            throw e;

        }
    }

    // Starts/Resumes the Thread
    public void Start()
    {
     /// Starts the Thread the first time
        if (captureThread.ThreadState == ThreadState.Unstarted)
        {
            _Communicator = selectedDevice.Open();
            captureThread.Start();
        }
     /// Resumes the Thread
        if (captureThread.ThreadState == ThreadState.WaitSleepJoin)
        {
            _pauseEvent.Set();
        }
    }


    public void Stop()
    {
        /// stop the thread
        _pauseEvent.Reset();
    }


// Starts to recieve packets
    public void StartListening()
    {
        try
        {
            _Communicator.ReceivePackets(0, HandlePacket);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


 // Handles Packet
    private void HandlePacket(Packet packet)
    {
        // some work..
    }

    #endregion

非常感谢!

4

1 回答 1

1

Stopping/Starting the thread is just the wrong way to do this. Have the thread run all the time, tell it when you want to stop/start capturing, and have it throw away/process the packets depending on that.

于 2014-01-22T08:38:33.777 回答