当前位置: 首页 > 编程语言 > C#

为我的下载器添加暂停和恢复功能分享

时间:2023-04-10 17:24:05 C#

为我的下载器添加暂停和恢复功能我正在用C#创建一个下载器。我正在使用WebClient类。要在按钮上暂停下载,我可以考虑使用Thread。因此,当我创建线程并将其附加到我的文件下载时,如下所示WebClientweb=newWebLCIent();Threaddwnd_thread=newThread(Program.web.DownloadFileAsync(newUri(Program.src),Program.dest));它给了我以下错误:“'System.Threading.Thread.Thread(System.Threading.ThreadStart)'的最佳重载方法匹配有一些无效参数”和“参数'1':无法从'void'转换为'System.Threading.ThreadStart'”。然后我想如果我暂停我的系统主线程那么它可以阻止我正在使用以下代码行的整个过程System.Threading.Thread.Sleep(100);但它什么都不做。有人可以告诉我暂停/下载的更好方法是什么以及如何使用线程暂停我的下载过程。由于没有暂停/恢复下载请求的标准方法,您必须实现自己的机制。下面是一段代码,其中包含此机制的示例。FileDownload类有3个参数:publicclassFileDownload{privatevolatilebool_allowedToRun;私有字符串_source;私有字符串_destination;私人int_chunkSize;私人懒惰_contentLength;publicintBytesWritten{得到;私有集;}publicintContentLength{get{return_contentLength.Value;}}publicboolDone{get{returnContentLength==BytesWritten;}}publicFileDownload(stringsource,stringdestination,intchunkSize){_allowedToRun=true;_source=来源;_destination=目的地;_chunkSize=块大小;_contentLength=newLazy(()=>Convert.ToInt32(GetContentLength()));写入的字节数=0;}privatelongGetContentLength(){varrequest=(HttpWebRequest)WebRequest.Create(_source);request.Method="HEAD";使用(varresponse=request.GetResponse())returnresponse.ContentLength;}privateasyncTaskStart(intrange){if(!_allowedToRun)thrownewInvalidOperationException();var请求=(HttpWebRequest)WebRequest。创建(_源);request.Method="GET";request.UserAgent="Mozilla/4.0(兼容;MSIE6.0;WindowsNT5.2;.NETCLR1.0.3705;)";请求.AddRange(范围);使用(varresponse=awaitrequest.GetResponseAsync()){使用(varresponseStream=response.GetResponseStream()){使用(varfs=newFileStream(_destination,FileMode.Append,FileAccess.Write,FileShare.ReadWrite)){while(_allowedToRun){varbuffer=newbyte[_chunkSize];varbytesRead=awaitresponseStream.ReadAsync(buffer,0,buffer.Length);如果(bytesRead==0)中断;等待fs.WriteAsync(buffer,0,bytesRead);BytesWritten+=bytesRead;}awaitfs.FlushAsync();}}}}publicTaskStart(){_allowedToRun=true;返回开始(BytesWritten);}publicvoidPause(){_allowedToRun=false;}}使用方法:staticvoidMain(string[]args){varfw=newFileDownload("http://download.microsoft.com/download/E/E/2/EE2D29A1-2D5C-463C-B7F1-40E4170F5E2C/KinectSDK-v1.0-Setup.exe",@"D:KinetSDK.exe",5120);//显示进度...Task.Factory.StartNew(()=>{while(!fw.Done){Console.SetCursorPosition(0,Console.CursorTop);Console.Write(string.Format("ContentLength:{0}|BytesWritten:{1}",fw.ContentLength,fw.BytesWritten));}});//开始下载...fw.Start();//模拟暂停...线程.Sleep(500);fw.Pause();Thread.Sleep(2000);//从我们离开的地方开始下载,完成后打印到控制台。fw.Start().ContinueWith(t=>Console.WriteLine("Done"));Console.ReadKey();}不幸的是,WebClient无法暂停下载,因此您必须在后台线程上使用WebRequest并暂停获取带有标志的响应流。这是示例代码。但请确保您可以t暂停,因为如果一段时间没有传输,TCP连接将被关闭。所以如果恢复下载失败,你必须重新开始下载。以上就是C#学习教程:在我的下载程序中添加暂停和继续功能,分享全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicclassDownloadJob{publicdelegatevoidDownloadCompletedDelegate(Streamstream);//完成下载事件publiceventDownloadCompletedDelegateOnDownloadCompleted;//同步对象privateobject_lock=newobject();//暂停标志privatebool_bPause=false;//暂停下载publicvoidPause(){lock(_lock){_bPause=true;}}//恢复下载publicvoidResume(){lock(_lock){_bPause=false;}}//使用URI开始下载publicvoidBeginDowload(Uriuri){//创建后台线程ThreaddownLoadThread=newThread(delegate(){WebRequestpWebReq=WebRequest.Create(uri);WebResponsepWebRes=pWebReq.GetResponse();using(MemoryStreampResultStream=newMemoryStream())using(StreampWebStream=pWebRes.GetResponseStream()){byte[]buffer=newbyte[256];intreadCount=1;while(readCount>0){//读取下载流读取计数=pWebStream.Read(buffer,0,buffer.Length);//写入结果MemoryStreampResultStream.Write(buffer,0,readCount);//当_bPause为真时等待100毫秒while(true){lock(_lock){if(_bPause==true){Thread.Sleep(100);}else{休息;}}}pResultStream.Flush();}//触发完成事件if(OnDownloadCompleted!=null){OnDownloadCompleted(pResultStream);}}});//启动后台线程作业downLoadThread.Start();}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: