Home > OS >  How to implement multithread server request? C#
How to implement multithread server request? C#

Time:10-04

everyone. Before I go into this, I'd like to say that I am rather new to C# but I am doing my best. Right now as a challenge for myself I took a test task from an IT company just for lulz, I am not going to aplly for the job, I was just curious how would real-life task look like.

Basically, what I need to do is: There's a server. I need to establish tcp\ip connection, send a certain string, get a string with symbols and numbers back, filter out and convert those numbers into int, put all of the ints into an array and calculate the mediane. I've managed to figure out all of this except for multithread request from server.

The catch is that when I request a number, there's a delay of 30-something seconds, so getting those numbers one by one is painstakingly long.

Here's my code:

static int[] numList = new int[2018];
private const int port = port;
private const string server = "Ip";
static TcpClient client = new TcpClient();

static void Main(string[] args)
{
    client.Connect(server, port);
    request2();

    foreach (var item in numList)
    {
        File.AppendAllText("FileONE.txt", item.ToString());
    }

    // Закрываем потоки
    client.Close();       
   
    Console.WriteLine("Запрос завершен...");
    Console.ReadKey();
}
public async static void request2()
{
    for (int i = 1; i <= 2018; i =5)
    {
        await Task.Run(() =>
        {
            //sending a string
            NetworkStream streamSend = client.GetStream();
            StreamWriter writer = new StreamWriter(streamSend);
            writer.WriteLine(i.ToString()   "\n");
            writer.Flush();

            //getting a string
            NetworkStream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);
            string message = reader.ReadLine();

            //filtering out
            string regex = message;
            string pattern = @"\d ";
            Regex rg = new Regex(pattern);
            MatchCollection match = rg.Matches(regex);

            int result = Convert.ToInt32(match[0].Value);
            Console.WriteLine(result);

            numList[i] = result;
       });
    }
}        

I know that I am calling the async method wrong so this is the question: How can I make my app to make simultaneous requests, filter the needed data and store in the array?

I see it like this: 5 async methods get those numbers and store them in the array, in the Main I sort the array and calculate the mediane. Can you guide me in the right direction towards getting async thing right?

CodePudding user response:

I've managed to achieve the desired work by writing this code:

 static void Main(string[] args)
    {

        var tasks = new[]
        {
            Task.Factory.StartNew(() => Request1(1,10)),
            Task.Factory.StartNew(() => Request1(11,20)),
           
    };
        Task.WaitAll(tasks);
        

        Console.WriteLine("Request complete...");
        Console.ReadKey();

    }

    public static void Request1(int start, int end)
    {
        
        for (int i = start; i <= end; i  )
        {
            try
            {
                //отправление сообщения
                TcpClient client = new TcpClient();
                client.Connect(server, port);
                NetworkStream streamSend = client.GetStream();
                StreamWriter writer = new StreamWriter(streamSend);
                string request = i.ToString()   "\n";
                writer.WriteLine(request);
                writer.Flush();

                //прием сообщения
                NetworkStream stream = client.GetStream();
                StreamReader reader = new StreamReader(stream);
                string message = reader.ReadLine();

                //обрабатываем строку
                string regex = message;
                string pattern = @"\d ";
                Regex rg = new Regex(pattern);
                MatchCollection match = rg.Matches(regex);
                //Console.WriteLine(regex);
                int result = Convert.ToInt32(match[0].Value);
                Console.WriteLine("Number "   i   ": "   result);
                numList[i] = result;
                File.AppendAllText("File2.txt", "Number "   i   ": "   result   "\n");
                
                reader.Close();
                writer.Close();
                client.Close();
            }

            catch
            {
                Console.WriteLine("Error in number "   i   ". Retrying...");
                i--;

            }
        }
                 
    }
  • Related