kapetan / dns

A DNS library written in C#
MIT License
415 stars 126 forks source link

Offloading Queries to Tasks #97

Open TheMasterofBlubb opened 1 year ago

TheMasterofBlubb commented 1 year ago

A simple Solution to Multithreading the Querying.

Concept: UdpClients Recieve Function is not Threadsafe, so it can only be one thread recieving. The Send Function is fully threadsafe (according to its source) as it doesnt use any buffers.

So on each recieved Query a task is spun up to find the adress to that query and send it back via the UdpClient. That creates a small overhead on each query, but allows to recieve further Queries while still working on one.

I used a small Benchmark (which is kinda finnicky to do without crashing somewhere on the socket) to determine an aprox speedup.

On my R9 5950X (32Threads, slight OC): Old implementation: ~5k requests/sec New Implementation: 7-8k requests/sec ~50% improvement

Requests were done on same PC using the Example project, woth this piece of code:

server.Listening += async (sender, e) => {
                int x = 2000;
                int y = 100;

                Stopwatch stopwatch = Stopwatch.StartNew();

                DnsClient client = new DnsClient("127.0.0.1", PORT);
                //16 Threads for sending seems to give best performance
                Parallel.For(0, x, new ParallelOptions() { MaxDegreeOfParallelism = 16}, c =>
                {
                    Task[] tasks = new Task[y];

                    for (int i = 0; i < y; i++)
                    {
                      tasks[i] = client.Lookup("google.com");
                    }
                    Task.WaitAll(tasks);

                    //This is needed to clean the Socket to not crash it
                    GC.Collect();                  
                });

                stopwatch.Stop();

                Console.WriteLine("Request per sec {0}", (x*y)/ (stopwatch.ElapsedMilliseconds/1000));

                server.Dispose();
            };