【发布时间】:2019-10-02 21:45:25
【问题描述】:
在我的 C# 应用程序中,我有一个 while 循环,它从 Redis 消息队列中收集一个字符串并将其发送到侦听服务器。 在每个 cicle 中,使用 HttpWebRequest Post 方法打开连接,并使用 StreamWriter 变量发送数据。 问题是:在发送两个字符串后,应用程序冻结而没有返回任何错误,它可能一分钟内什么也没做,之后它再次正常工作并继续为另外几个字符串工作,冻结等等。 调试显示 StreamWriter 变量声明期间发生延迟。
这里是核心代码:
// configure Redis
var redis = new RedisClient("127.0.0.1");
while (true)
{
// read from Redis queue
string json = redis.BRPop(30, "sensors_data");
//...
//URL DECLARATION
//...
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
SendDataAsync(json, url);
}
}
static async Task SendDataAsync(string json, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
try
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
Console.Write("Data Sent");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
catch (Exception err)
{
Console.Write(err.Message);
}
Console.WriteLine();
}
所以代码实际上可以工作,只是在声明 StreamWriter 时存在一些奇怪的巨大延迟。有人有什么主意吗?我不知道如何处理这个问题。
编辑
while (true)
{
i = 0;
// read from Redis queue
string json = redis.BRPop(30, "sensors_data");
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
try
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var response = httpWebRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string reply=reader.ReadToEnd();
Console.WriteLine(reply);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
catch (Exception err)
{
Console.Write(err.Message);
}
Console.WriteLine();
}
【问题讨论】:
-
“延迟”是您的代码读取来自
httpWebRequest.GetRequestStream()的响应。如果您希望您的应用程序响应,您可以使用 async/await 或后台工作人员进行处理。您应该使用什么取决于应用程序的上下文(甚至是什么)。 -
你真的在
while (true)循环中有这个吗? -
@Igor 我不习惯异步函数,所以我可能犯了一些错误,但即使 StteamWriter 被异步调用,问题仍然存在(如果我没有误解异步方法,这是对我来说比以前的问题更奇怪);无论如何,我的疑问是为什么在发送第二个字符串后读取 GetRequestStream() 需要更多时间,响应时间不应该或多或少相同吗?可能是由于某种原因代码无法获取流吗?
-
@Jimi 是的,代码是为了无限运行
-
这不是它的工作方式。您甚至没有等待服务器响应 StatusCode,因此您不知道服务器是否接受并处理了您尝试发送的信息(可能以 CPU 时钟速度)。这些只是关于这个主题的前几个注释。另外,你声明了你的方法
async,但它从未被等待(方法调用和其中的代码都没有),所以这段代码甚至不会编译。
标签: c# streamwriter