如何实现多线程服务器请求? C#
How to implement multithread server request? C#
各位。在开始之前,我想说我是 C# 的新手,但我正在尽力而为。现在作为对自己的挑战,我从一家 IT 公司接受了一个测试任务,只是为了 lulz,我不打算申请这份工作,我只是好奇现实生活中的任务会是什么样子。
基本上,我需要做的是:有一个服务器。我需要建立 tcp\ip 连接,发送某个字符串,返回一个带有符号和数字的字符串,过滤掉并将这些数字转换为 int,将所有 int 放入一个数组并计算中位数。除了来自服务器的多线程请求,我已经设法弄清楚了所有这些。
要注意的是,当我请求号码时,会有 30 秒左右的延迟,因此一个接一个地获取这些号码非常费时。
这是我的代码:
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;
});
}
}
我知道我错误地调用了异步方法,所以这就是问题:如何让我的应用程序同时发出请求、过滤所需数据并存储在数组中?
我是这样看的:5 个异步方法获取这些数字并将它们存储在数组中,在 Main 中我对数组进行排序并计算中位数。你能指导我朝着正确的方向前进吗?
我已经通过编写这段代码实现了预期的工作:
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--;
}
}
}
各位。在开始之前,我想说我是 C# 的新手,但我正在尽力而为。现在作为对自己的挑战,我从一家 IT 公司接受了一个测试任务,只是为了 lulz,我不打算申请这份工作,我只是好奇现实生活中的任务会是什么样子。
基本上,我需要做的是:有一个服务器。我需要建立 tcp\ip 连接,发送某个字符串,返回一个带有符号和数字的字符串,过滤掉并将这些数字转换为 int,将所有 int 放入一个数组并计算中位数。除了来自服务器的多线程请求,我已经设法弄清楚了所有这些。
要注意的是,当我请求号码时,会有 30 秒左右的延迟,因此一个接一个地获取这些号码非常费时。
这是我的代码:
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;
});
}
}
我知道我错误地调用了异步方法,所以这就是问题:如何让我的应用程序同时发出请求、过滤所需数据并存储在数组中?
我是这样看的:5 个异步方法获取这些数字并将它们存储在数组中,在 Main 中我对数组进行排序并计算中位数。你能指导我朝着正确的方向前进吗?
我已经通过编写这段代码实现了预期的工作:
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--;
}
}
}