背景
我正在构建一个远程c#应用程序,通过php服务器连接。它检查客户端程序是否被服务器识别,然后循环发送日志,如在线时间和检查命令。我模糊地评论了一些您可能不理解我为什么这样做的部分。
namespace Revamped_SERVER
{
class Program
{
static readonly String BASEURL = "http://mysite.com/index.php?";
static String OLD_ID = default(String);
static String CURRENT_ID = default(String);
static string GET(string PHP,Boolean IS_COMMAND)
{
using (WebClient CLIENT = new WebClient())
{
string RAW = CLIENT.DownloadString(BASEURL + PHP);
if (IS_COMMAND)
{
//this is a command, I remove the unique command ID so that previous commands and new ones aren't repeated if they have been submited more than once
CURRENT_ID = RAW.Remove(5, RAW.Length - 5);
return RAW.Remove(RAW.Length - 154, 154).Replace(CURRENT_ID, "");
}
else { return RAW.Remove(RAW.Length - 154, 154); } //this part removes extra string from server analytics a pain in the ***.
}
}
static string TIMESTAMP()
{
return DateTime.Now.ToString("M/d/yyy") + " - " + DateTime.Now.ToString("HH:mm:ss tt"); //Time to send to server
}
static void Main(string[] args)
{
using (WebClient CLIENT = new WebClient())
{
Boolean CONNECTED = false;
String Username = Environment.UserName;
while (true)
{
while (CONNECTED == false)
{
if (GET("REQUEST=ONLINE",false) == "TRUE")
{
CONNECTED = true;
}
}
if (CONNECTED)
{
if (GET("REQUEST=CHECK",false) == "FALSE")
{
CLIENT.OpenRead(BASEURL + "REQUEST=ADD");
}
CLIENT.OpenRead(BASEURL + "DATA=" + Username + "\r\nLast online at " + TIMESTAMP());
try
{
//this is where it gets stuck
String COMMAND = GET("REQUEST=COMMAND",true);
if (CURRENT_ID != OLD_ID)
{
OLD_ID = CURRENT_ID; //Set new ID
MessageBox.Show(COMMAND); //Show what Commands was sent by server
}
}
catch
{
CONNECTED = false;
}
}
}
}
}
}
}
的问题
在第一个循环中,它运行良好:连接,检查服务器是否识别它,然后检查命令。然而,当它再次循环时,它会发送日志,但仍然停留在:
String COMMAND = GET("REQUEST=COMMAND",true);
它没有给我任何错误但是当我将鼠标悬停在Web客户端上时它给了我这个:
我看了一下这篇文章,但它并没有向我解释如何在我的案例中避免这种情况。
http://blogs.msdn.com/b/jmstall/archive/2005/11/15/funceval-rules.aspx
这个WebClient被困在第二个循环上有什么问题?
的详情
答案 0 :(得分:1)
WebClient.OpenRead返回一个流,需要将其传递给流阅读器以读取响应。
在您的情况下,您根本没有使用返回的流。由于您正在重用webclient的实例,我猜这就是导致您提及的行为的原因。