@@ -21,6 +21,7 @@ You should have received a copy of the GNU Lesser General Public License
2121using System ;
2222using System . Collections . Generic ;
2323using System . ComponentModel ;
24+ using System . Runtime . CompilerServices ;
2425using System . Runtime . InteropServices ;
2526
2627namespace SharpPcap . LibPcap
@@ -279,12 +280,35 @@ public int GetNextPacketPointers(ref IntPtr header, ref IntPtr data)
279280 /// </summary>
280281 protected virtual void PacketHandler ( IntPtr param , IntPtr /* pcap_pkthdr* */ header , IntPtr data )
281282 {
282- unsafe
283+ var handle = Handle ;
284+ var gotRef = false ;
285+ try
283286 {
284- var pcapHeader = PcapHeader . FromPointer ( header ) ;
285- var dataSpan = new Span < byte > ( data . ToPointer ( ) , ( int ) pcapHeader . CaptureLength ) ;
286-
287- SendPacketArrivalEvent ( pcapHeader , dataSpan ) ;
287+ // Make sure that handle does not get closed until this function is done
288+ // See https://github.com/chmorgan/sharppcap/issues/343
289+ handle . DangerousAddRef ( ref gotRef ) ;
290+ if ( ! gotRef )
291+ {
292+ return ;
293+ }
294+ unsafe
295+ {
296+ var pcapHeader = PcapHeader . FromPointer ( header ) ;
297+ var dataSpan = new Span < byte > ( data . ToPointer ( ) , ( int ) pcapHeader . CaptureLength ) ;
298+ SendPacketArrivalEvent ( pcapHeader , dataSpan ) ;
299+ }
300+ }
301+ catch ( ObjectDisposedException )
302+ {
303+ // If Dispose was called in another thread, DangerousAddRef will throw this
304+ // Ignore
305+ }
306+ finally
307+ {
308+ if ( gotRef )
309+ {
310+ handle . DangerousRelease ( ) ;
311+ }
288312 }
289313 }
290314
0 commit comments