ダウンロードファイルバーの計算速度と進捗の背景労働者&進捗状況
ここではVB.NETのBackgroundworkerクラスだし、Web要求ファイルをダウンロードして開始するのに活用し、いくつかのコードがあります。 それだけでなく、ファイルの速度を計算することを示すそれは進行状況バーに。 全てのメインフォームは、利用しながら。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | 'Where the program save the file Delegate Sub ChangeTextsSafe ( ByVal length As Long , ByVal position As Integer , ByVal percent As Integer , ByVal speed As Double ) Delegate Sub DownloadCompleteSafe ( ByVal cancelled As Boolean ) Public Sub DownloadComplete ( ByVal cancelled As Boolean ) Me . txtFileName . Enabled = True Me . btnDownload . Enabled = True Me . btnCancel . Enabled = False If cancelled Then Me . Label4 . Text = "Cancelled" 'MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information) Else Me . Label4 . Text = "Successfully downloaded" 'MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Me . ProgressBar1 . Value = 0 Me . Label5 . Text = "Downloading: " Me . Label6 . Text = "Save to: " Me . Label3 . Text = "File size: " Me . Label2 . Text = "Download speed: " Me . Label4 . Text = "" End Sub Public Sub ChangeTexts ( ByVal length As Long , ByVal position As Integer , ByVal percent As Integer , ByVal speed As Double ) Me . Label3 . Text = "File size: " & Math. Round ( ( length / 1024 ) , 2 ) & " KB" Me . Label5 . Text = "Downloading: " & Me . txtFileName . Text Me . Label4 . Text = "Downloaded " & Math. Round ( ( position / 1024 ) , 2 ) & " KB of " & Math. Round ( ( length / 1024 ) , 2 ) & "KB (" & Me . ProgressBar1 . Value & "%)" If speed = - 1 Then Me . Label2 . Text = "Download speed: calculating..." Else Me . Label2 . Text = "Download speed: " & Math. Round ( ( speed / 1024 ) , 2 ) & " KB/s" End If Me . ProgressBar1 . Value = percent End Sub Private Sub btnDownload_Click ( ByVal sender As System. Object , ByVal e As System. EventArgs ) Handles btnDownload. Click If Me . txtFileName . Text <> "" AndAlso Me . txtFileName . Text . StartsWith ( "http://" ) Then Me . SaveFileDialog1 . FileName = Me . txtFileName . Text . Split ( "/" c ) ( Me . txtFileName . Text . Split ( "/" c ) . Length - 1 ) If Me . SaveFileDialog1 . ShowDialog = Windows. Forms . DialogResult . OK Then Me . whereToSave = Me . SaveFileDialog1 . FileName Me . SaveFileDialog1 . FileName = "" Me . Label6 . Text = "Save to: " & Me . whereToSave Me . txtFileName . Enabled = False Me . btnDownload . Enabled = False Me . btnCancel . Enabled = True Me . BackgroundWorker1 . RunWorkerAsync ( ) 'Start download End If Else MessageBox. Show ( "Please insert valid URL for download" , "Warning" , MessageBoxButtons. OK , MessageBoxIcon. Warning ) End If End Sub Private Sub btnCancel_Click ( ByVal sender As System. Object , ByVal e As System. EventArgs ) Handles btnCancel. Click Me . BackgroundWorker1 . CancelAsync ( ) 'Send cancel request Try Me . bckZip . CancelAsync ( ) Catch ex As Exception 'Do Nothing End Try End Sub Private Sub BackgroundWorker1_DoWork ( ByVal sender As System. Object , ByVal e As System. ComponentModel . DoWorkEventArgs ) Handles BackgroundWorker1. DoWork 'Creating the request and getting the response Dim theResponse As HttpWebResponse Dim theRequest As HttpWebRequest Try 'Checks if the file exist theRequest = WebRequest. Create ( Me . txtFileName . Text ) theResponse = theRequest. GetResponse theRequest. Timeout = 10000000 Catch ex As Exception MessageBox. Show ( "An error occurred while downloading file. Possibe causes:" & ControlChars. CrLf & _ "1) File doesn't exist" & ControlChars. CrLf & _ "2) Remote server error" , "Error" , MessageBoxButtons. OK , MessageBoxIcon. Error ) Dim cancelDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( cancelDelegate, True ) Exit Sub End Try Dim length As Long = theResponse. ContentLength 'Size of the response (in bytes) Dim safedelegate As New ChangeTextsSafe ( AddressOf ChangeTexts ) Me . Invoke ( safedelegate, length, 0 , 0 , 0 ) 'Invoke the TreadsafeDelegate Dim writeStream As New IO. FileStream ( Me . whereToSave , IO. FileMode . Create ) 'Replacement for Stream.Position (webResponse stream doesn't support seek) Dim nRead As Integer 'To calculate the download speed Dim speedtimer As New Stopwatch Dim currentspeed As Double = - 1 Dim readings As Integer = 0 Do If BackgroundWorker1. CancellationPending Then 'If user abort download Exit Do End If speedtimer. Start ( ) Dim readBytes ( 4096 ) As Byte Dim bytesread As Integer = theResponse. GetResponseStream . Read ( readBytes, 0 , 4096 ) nRead += bytesread Dim percent As Integer = ( nRead / length ) * 100 Me . Invoke ( safedelegate, length, nRead, percent, currentspeed ) If bytesread = 0 Then Exit Do writeStream. Write ( readBytes, 0 , bytesread ) speedtimer. Stop ( ) readings += 1 If readings > = 5 Then 'For increase precision, the speed it's calculated only every five cicles currentspeed = 20480 / ( speedtimer. ElapsedMilliseconds / 1000 ) speedtimer. Reset ( ) readings = 0 End If Loop 'Close the streams theResponse. GetResponseStream . Close ( ) writeStream. Close ( ) If Me . BackgroundWorker1 . CancellationPending Then IO. File . Delete ( Me . whereToSave ) Dim cancelDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( cancelDelegate, True ) Exit Sub End If Dim completeDelegate As New DownloadCompleteSafe ( AddressOf DownloadComplete ) Me . Invoke ( completeDelegate, False ) End Sub whereToSave として 暗い文字 列 'どこのプログラムがキャンセル保存するファイルの委任サブ ChangeTextsSafeを (ByVal DownloadComplete ブール値 )Public Sub を として( に対して 、ByVal 長としてロングは、ByValの整数 として 、位置に対して 、ByVal パーセントとして整数は は、ByValのダブルとして 速度 が )委任サブ ByVal DownloadCompleteSafe(キャンセル私はとして ブール値 )。txtFileName。有効 = Trueの場合は 私は私 btnDownload。有効 = Trueを 。btnCancelします 。 有効 = Falseに Meを次に 場合キャンセルされました。Label4します 。 本文 ="キャンセル "'します。MessageBox.Show("ダウンロード中止"、"中止"、 MessageBoxButtons.OK、MessageBoxIcon.Information)Else をMeを Label4。本文 ="正常にダウンロード "'します。MessageBox.Show("正常にダウンロード!"、""、MessageBoxButtons.OK、MessageBoxIcon.Information) エンド場合 Meを [OK]を全て 。ProgressBar1の値の = 0 Meは 。Label5の ダウンロード 。 テキストは =":" 私は Label6。テキストは ="に保存:"Me を Label3します 。 本文 ="ファイルサイズ:" 私 。Label2です 。 本文 ="ダウンロード速度:" 私 。Label4します 。 本文 =""End Subの パブリック サブ ChangeTexts(パーセントとしてByVal位置として 整数は、ByValのに対して、ByVal長限り 、 整数 として 、 ダブルスピードに対して、ByVal)さん 。Label3。本文 ="ファイルサイズ:"&数学。 ラウンド ((長さ/ 1024) 、2)&"KB の" 私 。Label5の ダウンロード 。 テキストは =":"&Meを txtFileName。本文 Meを Label4します 。 本文 ="ダウンロード"&数学。 ラウンドは ((位置/ 1024)、2)&"KB の" &数学。 ラウンド ((長さ/ 1024)、2)&" バイト("&Me を ProgressBar1の値の &"%)" もし速度= - 1 その後Meを Label2。本文 ="ダウンロード速度:計算..." 他の私は Label2。本文 ="ダウンロード速度は:"&数学。 ラウンド ((スピード/ 1024)、2)&" は、KBは/システムだ ByVal(btnDownload_Click送信として " 終了する場合 Meを ProgressBar1の値の =%のプライベート サブサブエンド 。 オブジェクトは 、ByVal電子EventArgs Asシステム。) 処理Meを クリックして ください 。btnDownload。txtFileName。本文 <>"を"AndAlso演算Meを txtFileNameします 。 本文。startswithは( 以下 "http://"で )そして Meを SaveFileDialog1。FileNameを = Meを txtFileNameを 。 本文です。Split("/"c)の(Me を txtFileName。本文です。Split("/"c)の 長さ - 1)Meを します 。SaveFileDialog1。ShowDialog = Windowsをフォーム。DialogResult OK]をクリックしMeを whereToSave = Meを 。 SaveFileDialog1。FileNameは 私は SaveFileDialog1。FileNameは ="" 私は Label6。テキストは ="に保存:"&Me をMeを whereToSave。txtFileNameします 。 有効 = Falseに Meを私 btnDownload。有効 = falseを返します 。btnCancelします 。 有効 = 真 さん 。BackgroundWorker1を 。RunWorkerAsync()'ダウンロード 終了する場合 [スタート] エルスメッセージ。 ショー ("URLのダウンロード"は有効な挿入してください、"警告"、MessageBoxButtons。[OK] を 、MessageBoxIcon。 警告 ) 終了する場合End Subの プライベート サブ btnCancel_Click(。 オブジェクトシステムByVal送信として 、 ByVal電子EventArgs としてシステム) を処理 btnCancelをクリックして Meを BackgroundWorker1。CancelAsync() の送信 Meを してください リクエストをキャンセルします。bckZipします。CancelAsync() キャッチシステムとして元として送信( に対して、ByVal BackgroundWorker1_DoWorkを例外が'何もしないエンド をお試しください プライベート サブサブエンド 。 オブジェクトは、ByVal電子DoWorkEventArgs としてシステム。ComponentModel) 処理 BackgroundWorker1。 次に示すとおり の要求を作成して)。txtFileName。本文Me を作成する(WebRequestクラスファイルは= 存在 theRequestを取得する場合、応答暗いtheResponse を付けて HttpWebResponseの暗い theRequest としてHttpWebRequestの は 、Try' をチェックしますとして例外メッセージ。 地図を表示する (theRequestのタイムアウト = 10000000 キャッチ元。 のGetResponse" エラーが発生しましたがダウンロードファイルをtheRequest = theResponse。Possibeは発生:"&ControlChars。CRLF は&_"1) ファイル&CRLF を。 しませんが存在する"&ControlChars _"2)リモートサーバーエラー"、"エラー"、MessageBoxButtons OK]をクリック。 エラー ) 暗い cancelDelegate として MessageBoxIcon 新 DownloadCompleteSafe( のAddressOf DownloadComplete) 私は 呼び出し (cancelDelegate、True)に 終了サブエンドしてください 。ContentLength theResponse 点心長 として ロング = バイト(の応答サイズ')。whereToSave 私 暗い safedelegateとして新ChangeTextsSafe( のAddressOf ChangeTexts) 私 は呼び出し(safedelegate、長さ、0、0、0として 新しいIO。WriteStreamの)' を呼び出しますTreadsafeDelegate暗い のFileStream(IO の 。 サポートしませんシーク) 点心を ストリーム FileModeを作成 ) するWebResponse(Stream.Position'交換のため として範囲の内容整数 ' として currentspeed speedtimerを付けて新しいストップウォッチ点心はDimの ために計算速度がダウンロードダブル = - 1 点心 の朗読として整数 = 0 BackgroundWorker1する場合に行う 。はspeedtimer CancellationPending 次に 場合 '場合は、ユーザーのアボート 終了しない終了を ダウンロード [ スタート]ボタン () 点心 readBytes(4096)整数 としての バイト として %の点心は bytesread として 整数 = theResponse。GetResponseStream。読む (readBytes、0、4096)範囲の内容+ = 暗い bytesread = (範囲の内容/長さ)* 100 Meは 。 呼び出し (safedelegate、長さ、範囲の内容、パーセントcurrentspeed)> が bytesread = 0の次に測定値が終了 readBytes、0、bytesread)speedtimer。 ストップ ()測定値+ = 1の 場合です WriteStreamの( 書くの = 5 Then'この精度を増加、速度はWriteStreamの ) です 計算のみすべて(5)speedtimer。リセット()測定値 = 0 終了 する場合ループは、[ 閉じるGetResponseStream を閉じる 。ストリームtheResponse cicles 1000 currentspeed = 20480 /(speedtimer. ElapsedMilliseconds / クローズ ()の 場合 。 ミー BackgroundWorker1。CancellationPending し IOの[ ファイルを 削除します ( 私は whereToSave) 点心 cancelDelegate として新 DownloadCompleteSafe( のAddressOf DownloadComplete) 私は 起動 (True)に 終了サブエンド場合 cancelDelegate completeDelegate として 暗い 新 DownloadCompleteSafe( のAddressOf DownloadComplete )Meを 起動 (completeDelegate、False)の End Subの |













































