开发者

Is Webclient's IWebProxy thread-safe?

开发者 https://www.devze.com 2023-01-18 20:10 出处:网络
When using WebClient to download data there seems to be some minor but perceivable delay incurred each time from resolving the proxy.Since I need to call the methods using the webclient multiple times

When using WebClient to download data there seems to be some minor but perceivable delay incurred each time from resolving the proxy. Since I need to call the methods using the webclient multiple times in different threads and webclient itself isn't thread safe I开发者_运维知识库 was thinking of instead just creating a new webclient each time and setting it's proxy to a pre-initialized IWebProxy

But is IWebProxy thread-safe so I can do this and is there possible some better way of doing this?


If you're seeing perf degradation from proxy lookup in .NET, here's several ways to address:

  1. construct a WebProxy object using a specific proxy host, rather than relying on .NET to use Web Proxy Auto-Discovery, which is probably causing the slowness you're seeing. This is workable in server scenarios, for example, where you can put the proxy server in a config file and forget about it. It's not workable in a client app where you don't know the proxy ahead of time.
  2. wrap a WebProxy object in your own IWebProxy implementation, and put a lock(this){ } around each interace method and property. Do this if you can't know the proxy in advance or setting a specific proxy doesn't help your perf problem.
  3. you can always download the .NET Framework Reference Source and look through the WebProxy implementation source code to see if it's actually thread safe, despite the documentation. I wouldn't advise this option but I'm including it here for completeness.

More info:

Interfaces (like IWebProxy) are neither thread-safe nor thread-unsafe. It's the implementations underneath them (like the WebProxy class) which determine thread safety.

That said, WebProxy is not thread safe. Per the MSDN Documentation for WebProxy:

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

BTW, the above (statics are thread-safe, instance methods/properties are not) is generally true for almost all classes in the .NET Framework. So unless you see documentation saying that instance methods are thread safe, then you should assume that instance methods/properties are not thread safe.

0

精彩评论

暂无评论...
验证码 换一张
取 消