我正在创建一个多线程random.org
数字getter来实现我的c#IRC bot。我遇到的问题是,它使用了相当大的内存占用。我认为这是WebClient
课程。我不喜欢它如何使用~5,000K
内存来连接到url,并读取第一行并输出数字。
对此更轻松吗?
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
Thread More = new Thread(GetRandomNum);
More.Start();
}
}
public static void GetRandomNum()
{
string number;
for (int i = 0; i < 100; i++)
{
using (WebClient client = new WebClient())
{
number = client.DownloadString("http://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new");
}
Console.WriteLine(number.Trim());
}
}
}
答案 0 :(得分:0)
WebRequest可以解决问题。
WebRequest request = WebRequest.Create ("http://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new");
// If required by the server, set the credentials.
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
// Display the status.
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
这看起来非常复杂,代码仍然相当简单明了。 内存消耗必须远低于WebClient。