抛出System.OutOfMemoryException'-WebClient.DownloadStringAsynch() [英] System.OutOfMemoryException' was thrown - WebClient.DownloadStringAsynch()

查看:154
本文介绍了抛出System.OutOfMemoryException'-WebClient.DownloadStringAsynch()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个性能较差的Mans Load Tester,我认为我正在正确地管理我的资源(线程池),但是当我运行以下代码时,我在调用WebClient.DownloadStringAsynch时收到OutOfMemoryException.

I'm writing a poor mans load tester and I thought I was managing my resources correctly (thread pool) but when I run the following code I get an OutOfMemoryException on my call to WebClient.DownloadStringAsynch.

使用.net4.0,但可能会移至4.5.

Using .net4.0 but could move to 4.5.

询问:

  • 解决方法是什么?
  • 我如何使用HttpWebRequest并将该异步发送给Webclient?
  • 使用.net 4.5使用await怎么样(与.net4通过异步调用管理线程的方式有何不同?

  • What is the fix?
  • How could I use HttpWebRequest and send that asynch as an alternative to webclient?
  • What about using .net 4.5 using await (any difference with how .net4 manages threads with asynch calls?

static void Main(string[] args)
{
    System.Net.ServicePointManager.DefaultConnectionLimit = 200;
    while (true)
    {
        for (int i = 0; i < 100; i++)
        {
            Task.Factory.StartNew(LoadTestAsynchNET40);
        }
        Console.WriteLine(".........................sleeping...............................");
        Thread.Sleep(2);
    }
}

static void LoadTestAsynchNET40()
{
  string url = "http://mysrv.com/api/dev/getthis?stuff=thestuff" + "&_=" + DateTime.Now.Ticks;  // <--- somtimes throws here...
    using (var client = new WebClient())
    {
        DateTime dt1 = DateTime.Now;
        client.Headers["Accept"] = "text/xml";
        client.DownloadStringCompleted += DownloadStringCompleted;
        Console.WriteLine(DateTime.Now.ToString("ss:fff") + ", Sent Ad Request...");
        client.DownloadStringAsync(new Uri(url), dt1); //<---throws here...
    }
}

static void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    Console.WriteLine("Received reponse...");

}

推荐答案

DownloadStringAsync将创建一个包含整个响应的巨型字符串.
如果您要求大量答复,那么将耗尽内存.

DownloadStringAsync will create a single giant string containing the entire response.
If you call that for lots of big responses, you will run out of memory.

相反,您应该直接使用HttpWebRequest.
它的GetResponse()(或BeginGetResponse())方法为您提供了 stream ,它使您可以直接从服务器读取响应,而无需将其缓冲在内存中.

Instead, you should use HttpWebRequest directly.
Its GetResponse() (or BeginGetResponse()) method gives you a stream that allows you to read the response directly from the server without buffering it in memory.

如果仍然需要异步,则应移动.Net 4.5,这将添加易于使用的GetResponseAsync()方法(与基于APM的旧BeginGetResponse()相对)

If you still want asyncrony, you should move the .Net 4.5, which adds the easier-to-use GetResponseAsync() method (as opposed to the old APM-based BeginGetResponse())

这篇关于抛出System.OutOfMemoryException'-WebClient.DownloadStringAsynch()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆