并发线程在套接字上发送数据的速度较慢?

Jos*_*low -1 c# multithreading

下面我有一个应用程序,我试图使用C#套接字以尽可能快的方式发送尽可能多的数据.数据启动10秒后,我停止数据发送并等待控制台密钥,同时向控制台写入已发送的请求数.

当将线程数量设置为1时,我达到了更高的请求.这是日志

Attempt 1    => 86873
Attempt 2    => 107324
Attempt 3    => 97426
Attempt 4    => 94720
Attempt 5    => 97927
Attempt 6    => 94327
Attempt 7    => 94791
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,它的峰值在80,000到110,000之间.当它设置为高于1的任何值时(我试过1和2)它甚至没有达到80,000,它在10秒内达到约70-75,000.我的想法是更多的线程=更多的数据发送,因为它在幕后做了更多的工作?谁能给我一些关于此的信息?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RDOS
{
    public class ThreadHandler
    {
        private int count = 0;
        private int threadCount = 3;
        private List<Thread> _threads = new List<Thread>();

        private string _ip;
        private int _port;

        public int RequestsSent;
        public int RequestsFailed;
        public DateTime Started;

        public ThreadHandler()
        {
            Console.Write("IP: ");
            _ip = Console.ReadLine();

            Console.Write("Port: ");
            _port = int.Parse(Console.ReadLine());

            Console.WriteLine("sending data to " + _ip + " on port " + _port);

            Thread backgroundThread = new Thread(new ThreadStart(OnBackgroundThread));
            backgroundThread.Start();

            for (int i = 0; i < threadCount; i++)
            {
                _threads.Add(new Thread(new ThreadStart(OnThread)));
            }

            foreach (Thread thread in _threads)
            {
                thread.Start();
            }
        }

        public void OnBackgroundThread()
        {
            Started = DateTime.Now;

            while (true)
            {
                System.Threading.Thread.Sleep(10000);
                TimeSpan span = DateTime.Now - Started;
                Console.WriteLine("Sent " + RequestsSent + " requests (running for " + span.TotalSeconds + ")");
                Console.ReadKey();
            }
        }

        public void OnThread()
        {
            IPEndPoint RHost = new IPEndPoint(IPAddress.Parse(_ip), _port);

            using (Socket socket = new Socket(RHost.AddressFamily, SocketType.Dgram, ProtocolType.Udp))
            {
                socket.Blocking = true;

                while (true)
                {
                    RequestsSent++;
                    byte[] buf = System.Text.Encoding.ASCII.GetBytes("fwkdkskdsksk");
                    socket.SendTo(buf, SocketFlags.None, RHost);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ain 6

除了线程安全错误导致你低于实际数字,虽然你可能有多个线程,但你仍然只有一个网络适配器,这可能是你的瓶颈所在.

在I/O绑定问题上投入更多CPU功率不会让您获得更快的I/O,事实上大多数情况下,由于操作系统必须执行的锁定所带来的开销,它会导致I/O速度变慢序列化访问I/O设备.获得更快I/O的唯一方法是获得更快的硬件.