C#用WebClient下载File时操作超时的问题


使用WebClient下载文件,结果发现只能下载一个文件,第二次下载的时候就会出现“操作超时”的问题。


这个是原代码:

System.Net.WebClient wc = new System.Net.WebClient();  
wc.OpenRead("http://patrickkroft.com/mp3/Pearl.mp3");  
Int64 bytes_total= Convert.ToInt64(wc.ResponseHeaders["Content-Length"])  
MessageBox.Show(bytes_total.ToString() + " Bytes");  


以上的代码实在是很不负责,坑爹的写的。改进成下面:


System.Net.WebClient wc = new System.Net.WebClient();  
Stream stream = wc.OpenRead(folderEntity.URI);  
Int64 bytes_total = Convert.ToInt64(wc.ResponseHeaders["Content-Length"]);  
stream.Close();  //以及释放内存  
wc.Dispose(); //及时释放,避免第二次下载时, 奇怪的"操作超时"的问题  


原文地址:http://www.cnblogs.com/webfpc/archive/2012/09/26/2704365.html


.net C#线程超时的解决方案,使用的候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的ThreadID [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] public static extern Int32 GetCurrentWin32ThreadID(); #endregion #region 登记访问任务子线程 /// /// 访问任务子线程 /// public static Hashtable TaskThreadIDTable = Hashtable.Synchronized(new Hashtable()); private static int[] TaskThreadIDs { get { int[] IDs = new int[TaskThreadIDTable.Keys.Count]; TaskThreadIDTable.Keys.CopyTo(IDs, 0); return IDs; } } public static void RegisterThread(int _threadid, System.Threading.Thread thread) { if (!TaskThreadIDTable.ContainsKey(_threadid)) TaskThreadIDTable.Add(_threadid, thread); if (!ExitInvalidThreadLoopRunning) { Thread ExitInvalidThreadLoopThread = new Thread(new ThreadStart(ExitInvalidThreadLoop)); ExitInvalidThreadLoopThread.Priority = ThreadPriority.AboveNormal; ExitInvalidThreadLoopThread.Start(); } } #endregion #region 关闭,退出超时的用户线程 private static DateTime ExitInvalidThreadLoop_LastRunTime = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); private static bool ExitInvalidThreadLoopRunning { get { return DateTime.Now.Subtract(ExitInvalidThreadLoop_LastRunTime).TotalMinutes 10) { try { Thread thread = (Thread)TaskThreadIDTable[t.Id]; thread.Abort(); } catch { } t.Dispose(); } } #endregion } #endregion
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值