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

时间:2017-05-05 13:44:05

标签: 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

正如你所看到的那样,它的峰值在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);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:6)

除了the thread safety error which is causing you to get lower than actual numbers之外,虽然你可能有多个线程,但你仍然只有一个网络适配器,这可能就是你的瓶颈所在。

在I / O限制问题上投入更多的CPU能力不会让你的I / O更快,实际上大多数时候它会导致你的I / O速度变慢,因为操作系统已经锁定了开销。要序列化对I / O设备的访问。获得更快I / O的唯一方法是获得更快的硬件。