WebClient construction overhead

微笑、不失礼 提交于 2019-12-10 12:35:30

问题


I have a client which makes a limited number of concurrent web requests. I use WebClient for this purpose. I currently have a pool of WebClient-s which I create once and use whichever one is idle.

This approach is becoming a little cumbersome though, and I'm wondering if there is any benefit to having a collection of pre-constructed WebClient instances, or if creating them on the fly wouldn't be too much trouble?


回答1:


Why on earth would you have a pool of WebClients in the first place? They are tiny, cheap objects. Did you determine by measuring that this is needed and beneficial? I assume not?

Object instantiation is almost always cheap. HTTP connections are not expensive, either. A WebClient pool is premature optimization. There is no need for it - feel free to create as many as you want.




回答2:


According to Reflector all that the constructor of WebClient does is this:

public WebClient()
{
    this.m_Encoding = Encoding.Default;
    this.m_ContentLength = -1L;
}

So no you have not much benefit of having a pool.




回答3:


If you are using .NET 4.0 you can parallelize the Web Requests. Check this out.

But to the real question, I wouldn't store the instances of the WebClient in an Array, if there is no need to re-use that instance on other places. Depending on the purpose and the kind of usage you could aswell have a Request Pool with a String Dictionary.

And then just re-use a WebClient instead of having multiple instances.



来源:https://stackoverflow.com/questions/2492011/webclient-construction-overhead

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!