轉自:http://www.cnblogs.com/xunziji/archive/2011/01/24/1943092.html
今天利用 WebClient 的 DownloadData、DownloadFileAsync 等方法跨域請求資料時,沒有發現什麼問題。可是過了半天,查看錯誤記錄檔時,卻大吃了一驚,發現好多 WebClient does not support concurrent I/O operations 的錯誤資訊。仔細查看 錯誤資訊的 堆棧後,把出錯的方法和URL Copy在瀏覽器中執行,輸入相應的參數,卻發現是可以調用的,這個就很鬱悶了,看來這個錯誤不是每次調用都出現,就更難排查了。
最後,google 了半天,並看了許多資料,發現 只要錯誤資訊含有 does not support concurrent I/O operations 資訊的,都是由 一個執行個體同時在多個地方調用產生的,通俗易懂的說,就是並發引起的。下面摘錄一句google到得解釋:
I don't think you can use a single WebClient instance to execute several
HTTP requests at the same time. Try to create a WebClient instance per request,
that should work just fine.
最後在貼出來一下自己的代碼:
private static WebClient WC;
static Test()
{
WC = new WebClient();
WC.Headers["User-Agent"] = Config.Host + "|" + ServiceKey;
}
原來自己的 WebClient 是靜態全域的,所以,並發使用 WC 來操作資料的時間,就報了上述錯誤
解決辦法:每個使用到 WebClient 的地方,都 new 一個 WebClient 執行個體,防止出現並發。同時 does not support concurrent I/O operations 錯誤的方法,一般也是由於 並發引起的,解決方案請參照上一句。