I am getting extremely bad download performance out of WinDivert and need help fixing it. I am using WinDivertSharp version 1.4.3.3 for my .NET C# application in tandem with the WinDivert driver. It runs fine but when I use speedtest.net my download speed gets more than halved while my ping gets quintupled. The odd thing is my download speed stays relatively static with and without using it. This made me think that maybe since my download is so much greater than my upload my C# thread is bottlenecking? If that is the case is there a way, I can run multiple threads to handle this or something?
Here is my code where right now I am creating another thread to receive network packets from incoming and outgoing UDP and TCP. I then add the WinDivertParseResult to a BlockingCollection where another thread waits on entries being added so that I can add them to the UI without blocking the thread that is listening for network traffic.
private readonly BlockingCollection<WinDivertParseResult> packetCollection = new
BlockingCollection<WinDivertParseResult>();
private void StartPacketCapture()
{
Thread captureThread = new Thread(() =>
{
IntPtr handle = WinDivert.WinDivertOpen("(inbound || outbound) && (tcp && udp)", // Filter to capture all TCP and UDP traffic outbound && (tcp || udp)
WinDivertLayer.Network, 0, WinDivertOpenFlags.None);
if (handle == IntPtr.Zero) return;
WinDivertBuffer packets = new WinDivertBuffer();
WinDivertAddress addr = new WinDivertAddress();
uint recvLen = 0;
while (true)
{
addr = new WinDivertAddress();
if (!WinDivert.WinDivertRecv(handle, packets, ref addr, ref recvLen))
{
int errorCode = Marshal.GetLastWin32Error();
Console.WriteLine($"Failed to receive packet, Error code: {errorCode}");
WinDivert.WinDivertSend(handle, packets, recvLen, ref addr);
continue;
}
// Parse the packet using WinDivertSharp
WinDivertParseResult parseResult = WinDivert.WinDivertHelperParsePacket(packets, recvLen);
unsafe
{
if (handle == IntPtr.Zero)
{
Console.WriteLine("Failed to open WinDivert handle.");
return;
}
if (parseResult == null || parseResult.IPv4Header == null) // Check if it is a TCP packet
{
WinDivert.WinDivertSend(handle, packets, recvLen, ref addr); // Re-inject non-TCP or unparsed packets
continue;
}
if (parseResult.TcpHeader != null)
{ // Handle TCP code
packetCollection.Add(parseResult);
}
else if (parseResult.UdpHeader != null)
{ // Handle UDP code
packetCollection.Add(parseResult);
}
WinDivert.WinDivertSend(handle, packets, recvLen, ref addr);
}
}
});
captureThread.Priority = ThreadPriority.Highest;
captureThread.IsBackground = true;
captureThread.Start();
}
Another thing to note is when commenting out all of my code and just sending new packets with WinDivert.WinDivertSend
inside the while loop I continue to receive extremely poor performance which is how I can to the conclusion above.