I am trying to upload a file using a thread. I have placed a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
Method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When someone clicks on the same button simultaneously the thread behavior works in a different way, some time page crashes.
When this process I have tested on multi-user environment with 60 users and file size is 25 mb each user the page crashed.
I have to use .NET 3.5 so I cannot use the advanced version of file upload in 2010 or later.
Error : 1-File uploding is more than 15 minutes but still in progress 2- Internet explorer cannot explore the page -Diagnose Internet problems 3- some user get login probem to the server on which the site has hosted
The course I usually take in .NET is to use ThreadPool.QueueUserWorkItem
If you do this with anonymous lambdas, I find it makes the syntax and life rather nice. You can do something like this:
btnUpload.Enabled = False
ThreadPool.QueueUserWorkItem(Sub()
SaveFileByBuffering(FldUploadThreading.FileName)
RaiseEvent EnableButton
End Sub)
With this event handler:
Public Sub EnableButton() Handles EnableButton
If Me.InvokeRequired Then
Me.BeginInvoke(Sub() EnableButton())
Else
btnUpload.Enabled = True
EndIf
EndSub
My .NET is rusty and I don't have a compiler anywhere, but doing something like this should handle most of your issues.
Related
I am having a program in VB, which searches for image in a website as follows:
www.website.com/1.jpg | www.website.com/2.jpg | www.website.com/3.jpg
in loop, and the program opens up only 3.jpg in browser, since 1 and 2 jpg does not exit in server. The program is up and running, but is very very slow, around 120 searches in a minute. However one of my colleagues designed the same program in Angular and that program is running very fast, around 500/600 searches in a minute.
He told me, what he did is generated 50 asynchronous calls to server, and then again 50, and then again 50 and went on like this. thus making his program very fast and ovbiously accurate.
I studied and learnt, that in Visual Basic too, we have async and wait calls to server request, but I cannot figure out how.
Here goes my existing code. Can anyone help me.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim MYURL as string
itemsF = 0
While Not itemsF = 50000
MYURL = "www.website.com/" & itemsF & ".jpg"
CheckPageExists(MYURL)
itemsF=itemsF+1
End While
End Sub
Private Function CheckPageExists(ByVal url As String) As Boolean
Dim request As Net.HttpWebRequest
Dim response As Net.HttpWebResponse
request = Net.WebRequest.Create(url)
request.Timeout = 5000
Try
response = request.GetResponse()
Catch ex As Exception
'IMAGE DOES NOT EXITS
Exit Function
End Try
Process.Start(url)
End Function
First, you have to make CheckPageExists an Async method:
Private Async Function CheckPageExists(ByVal url As String) As Task(Of Boolean)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(url)
request.Timeout = 5
Dim Result As Boolean
Try
Using response As HttpWebResponse = Await request.GetResponseAsync.ConfigureAwait(False)
Using responseReader As New IO.StreamReader(response.GetResponseStream)
Dim actualResponse As String = Await responseReader.ReadToEndAsync
Result = True
End Using
End Using
Catch ex As Exception
'IMAGE DOES NOT EXITS
Result = False
End Try
Console.WriteLine(url)
''Process.Start("chrome.exe", url)
Return Result
End Function
As you can see, instead of GetResponse we are using GetResponseAsync, which is Async itself. This method is very similar to what you were doing before, I
just added Return statements for clarity and a StreamReader to read the response of your website.
Once you've done that, you just need to change your Button2_Click method to call this other method, which incorporates all you were doing before:
Async Function MakeRequests() As Task
Dim tasks As List(Of Task(Of Boolean)) = New List(Of Task(Of Boolean))
Dim itemsF As Integer = 5
For i = 1 To itemsF
Dim MYURL As String = "http://www.touchegolfschool.com/images/" & i & ".jpg"
tasks.Add(CheckPageExists(MYURL))
Next
While tasks.Select(Function(x) x.Result).Count < tasks.Count
Thread.Sleep(100)
End While
End Function
The main change was adding tasks.Select(Function(x) x.Result).Count < tasks.Count; what you were seeing before was a request made but never returning because of the time it took to return; telling the main function to wait until all requests have a result makes the application wait long enough for the responses to come.
Here the main difference is the use of Tasks.
Check this for official documentation on asynchronous programming.
This is the modified code about uploadsession soo at small size file it working like a charm but when I try larger file like 5mb up. The following error keep showing up :
+$exception {"lookup_failed/closed/..."} System.Exception {Dropbox.Api.ApiException}
Private Async Sub UploadToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles UploadToolStripMenuItem2.Click
Dim C As New OpenFileDialog
C.Title = "Choose File"
C.Filter = "All Files (*.*)|*.*"
If C.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fileinfos = Path.GetFileName(C.FileName)
Dim filetempat = Path.GetFullPath(C.FileName)
Dim tempat As String = direktori.Text & "/" & fileinfos
Await Upload(filetempat, tempat)
End If
End Sub
Async Function Upload(localPath As String, remotePath As String) As Task
Const ChunkSize As Integer = 4096 * 1024
Using fileStream = File.Open(localPath, FileMode.Open)
If fileStream.Length <= ChunkSize Then
Await A.Files.UploadAsync(remotePath, body:=fileStream)
Else
Await Me.ChunkUpload(remotePath, fileStream, ChunkSize)
End If
End Using
End Function
Private Async Function ChunkUpload(path As [String], stream As FileStream, chunkSize As Integer) As Task
Dim numChunks As Integer = CInt(Math.Ceiling(CDbl(stream.Length) / chunkSize))
Dim buffer As Byte() = New Byte(chunkSize - 1) {}
Dim sessionId As String = Nothing
For idx As Integer = 0 To numChunks - 1
Dim byteRead = stream.Read(buffer, 0, chunkSize)
Using memStream = New MemoryStream(buffer, 0, byteRead)
If idx = 0 Then
Dim result = Await A.Files.UploadSessionStartAsync(True, memStream)
sessionId = result.SessionId
kondisi.Text=byteRead
Else
Dim cursor = New UploadSessionCursor(sessionId, CULng(CUInt(chunkSize) * CUInt(idx)))
If idx = numChunks - 1 Then
Dim fileMetadata As FileMetadata = Await A.Files.UploadSessionFinishAsync(cursor, New CommitInfo(path), memStream)
MessageBox.Show("Upload Complete")
Console.WriteLine(fileMetadata.PathDisplay)
Else
Await A.Files.UploadSessionAppendV2Async(cursor, True, memStream)
MessageBox.Show("Upload Failed")
End If
End If
End Using
Next
End Function
okay now its fixed, but when i got home, and try this code at my home,i got error, is this method are affected by slow internet connection ?.cause my campus have a decent speed.
this is the error message
+$exception {"Cannot access a disposed object.\r\nObject name: 'System.Net.Sockets.Socket'."} System.Exception {System.ObjectDisposedException}
this Cannot obtain value of local or argument '<this>' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.Socket
asyncResult Cannot obtain value of local or argument 'asyncResult' as it is not available at this instruction pointer, possibly because it has been optimized away. System.IAsyncResult
errorCode Cannot obtain value of local or argument 'errorCode' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.SocketError
this error window i got
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.
This Closed error indicates you can't continue uploading to the upload session because it's already been closed.
The UploadSessionStartAsync and UploadSessionAppendV2Async both take a bool parameter called close, which closes the session.
You're always setting that to True when you call those, closing the sessions. You shouldn't close a session until you're finished uploading data for it.
I'm using this code to encrypt/decrypt files:
Public Shared Sub encryptordecryptfile(ByVal strinputfile As String, _
ByVal stroutputfile As String, _
ByVal bytkey() As Byte, _
ByVal bytiv() As Byte, _
ByVal direction As CryptoAction)
Try
fsInput = New System.IO.FileStream(strinputfile, FileMode.Open, FileAccess.Read)
fsOutput = New System.IO.FileStream(stroutputfile, FileMode.OpenOrCreate, FileAccess.Write)
fsOutput.SetLength(0)
Dim bytbuffer(4096) As Byte
Dim lngbytesprocessed As Long = 0
Dim lngfilelength As Long = fsInput.Length
Dim intbytesincurrentblock As Integer
Dim cscryptostream As CryptoStream
Dim csprijndael As New System.Security.Cryptography.RijndaelManaged
Select Case direction
Case CryptoAction.ActionEncrypt
cscryptostream = New CryptoStream(fsOutput, _
csprijndael.CreateEncryptor(bytkey, bytiv), _
CryptoStreamMode.Write)
Case CryptoAction.ActionDecrypt
cscryptostream = New CryptoStream(fsOutput, _
csprijndael.CreateDecryptor(bytkey, bytiv), _
CryptoStreamMode.Write)
End Select
While lngbytesprocessed < lngfilelength
intbytesincurrentblock = fsInput.Read(bytbuffer, 0, 4096)
cscryptostream.Write(bytbuffer, 0, intbytesincurrentblock)
lngbytesprocessed = lngbytesprocessed + CLng(intbytesincurrentblock)
End While
cscryptostream.Close()
fsInput.Close()
fsOutput.Close()
Catch ex As Exception
End Try
End Sub
Is I need to get the percentage of this process being done as an integer. I am going to use a background worker, so I need to call for this sub from the background worker and be able to keep refreshing a progress bar that the background worker reports to. Is this possible?
Thanks in advance.
There are a couple of things you can do to make your cryptor more efficient and other issues:
A method like encryptordecryptfile which then requires a "mode" argument to know which action to take means it really might be better off as 2 methods
The way you are going, you will be raising a blizzard of ProgressChanged events which the ProgressBar wont be able to keep up with given the animation. A 700K file will result in 170 or so progress reports of tiny amounts
Some of the crypto steps can be incorporated
You have a lot of things not being disposed of; you could run out of resources if you run a number of files thru it in a loop.
It might be worth noting that you can replace the entire While block with fsInput.CopyTo(cscryptostream) to process the file all at once. This doesnt allow progress reporting though. Its also not any faster.
Rather than a BackgroundWorker (which will work fine), you might want to implement it as a Task. The reason for this is that all those variables need to make their way from something like a button click to the DoWork event where your method is actually called. Rather than using global variables or a class to hold them, a Task works a bit more directly (but does involve one extra step when reporting progress). First, a revised EncryptFile method:
Private Sub EncryptFile(inFile As String,
outFile As String,
pass As String,
Optional reporter As ProgressReportDelegate = Nothing)
Const BLOCKSIZE = 4096
Dim percentDone As Integer = 0
Dim totalBytes As Int64 = 0
Dim buffSize As Int32
' Note A
Dim key = GetHashedBytes(pass)
Dim iv = GetRandomBytes(16)
Dim cryptor As ICryptoTransform
' Note B
Using fsIn As New FileStream(inFile, FileMode.Open, FileAccess.Read),
fsOut As New FileStream(outFile, FileMode.OpenOrCreate, FileAccess.Write)
fsOut.SetLength(0)
' Note C
'ToDo: work out optimal block size for Lg vs Sm files
If fsIn.Length > (2 * BLOCKSIZE) Then
' use buffer size to limit to 20 progress reports
buffSize = CInt(fsIn.Length \ 20)
' to multiple of 4096
buffSize = CInt(((buffSize + BLOCKSIZE - 1) / BLOCKSIZE) * BLOCKSIZE)
' optional, limit to some max size like 256k?
'buffSize = Math.Min(buffSize, BLOCK256K)
Else
buffSize = BLOCKSIZE
End If
Dim buffer(buffSize-1) As Byte
' Note D
' write the IV to "naked" fs
fsOut.Write(iv, 0, iv.Length)
Using rij = Rijndael.Create()
rij.Padding = PaddingMode.ISO10126
Try
cryptor = rij.CreateEncryptor(key, iv)
Using cs As New CryptoStream(fsOut, cryptor, CryptoStreamMode.Write)
Dim bytesRead As Int32
Do Until fsIn.Position = fsIn.Length
bytesRead = fsIn.Read(buffer, 0, buffSize)
cs.Write(buffer, 0, bytesRead)
If reporter IsNot Nothing Then
totalBytes += bytesRead
percentDone = CInt(Math.Floor((totalBytes / fsIn.Length) * 100))
reporter(percentDone)
End If
Loop
End Using
Catch crEx As CryptographicException
' ToDo: Set breakpoint and inspect message
Catch ex As Exception
' ToDo: Set breakpoint and inspect message
End Try
End Using
End Using
End Sub
Note A
One of the standard crypto tasks it could handle is creating the Key and IV arrays for you. These are pretty simple and could be shared/static members.
Public Shared Function GetHashedBytes(data As String) As Byte()
Dim hBytes As Byte()
' or SHA512Managed
Using hash As HashAlgorithm = New SHA256Managed()
' convert data to bytes:
Dim dBytes = Encoding.UTF8.GetBytes(data)
' hash the result:
hBytes = hash.ComputeHash(dBytes)
End Using
Return hBytes
End Function
Public Shared Function GetRandomBytes(size As Integer) As Byte()
Dim data(size - 1) As Byte
Using rng As New RNGCryptoServiceProvider
' fill the array
rng.GetBytes(data)
End Using
Return data
End Function
As will be seen later, you can store the IV in the encrypted file rather than saving and managing it in code.
Note B
Using blocks close and dispose of resources for you. Basically, if something has a Dispose method, then you should wrap it in a Using block.
Note C
You dont want to report progress for every block read, that will just overwhelm the ProgressBar. Rather than another variable to keep track of when the progress has changed by some amount, this code starts by creating a buffer size which is 5% of the input file size so there will be about 20 reports (every 5%).
As the comments indicate, you may want to add some code to set minimum/maximum buffer size. Doing so would change the progress report frequency.
Note D
You can write the IV() to the filestream before you wrap it in the CryptoStream (and of course read it back first when Decrypting). This prevents you from having to store the IV.
The last part is kicking this off as a Task:
Dim t As Task
t = Task.Run(Sub() EncryptFile(inFile, oFile, "MyWeakPassword",
AddressOf ReportProgress))
...
What a BGW does is execute the work on one thread, but progress is reported on the UI thread. As a Task, all we need to do is use Invoke:
Delegate Sub ProgressReportDelegate(value As Int32)
Private Sub ReportProgress(v As Int32)
If progBar.InvokeRequired Then
progBar.Invoke(Sub() progBar.Value = v)
Else
progBar.Value = v
progBar.Invalidate()
End If
End Sub
The Encryptor will work either directly or as a Task. For small files, you can omit the progress report entirely:
' small file, no progress report:
EncryptFile(ifile, oFile, "MyWeakPassword")
' report progress, but run on UI thread
EncryptFile(ifile, oFile, "MyWeakPassword",
AddressOf ReportProgress)
' run as task
Dim t As Task
t = Task.Run(Sub() EncryptFile(ifile, oFile, "MyWeakPassword",
AddressOf ReportProgress))
...and if you had a list of files to do, you could run them all at once and perhaps report total progress.
Boy, learning something new can be a real headache if you can't find a solid source. I have been designing applications in a linear fashion for some time now and want to step up into a more powerful approach. I have been reading up on threading, and perhaps have gone to an larger level than I should. However, one usually steps up when the application calls for it and no better time than the present to learn something new.
My program is designed to do something that seems rather simple, but has become extremely difficult to create in a smooth running manor. The original design created object of each device on the network it wished to ping, in my real world environment they are Kindles. The goal was to ensure they were still connected to the network by Pining them. I used a For Loop and Obj Array to do this set on a Timer. This had unexpected results causing the ListView to flicker and load slowly after the ListView1.Items.Clear. I evolved into updating the List Items rather than clearing them and the flicker remained.
I assumed this was due to the slow process of the array and pings so I started hunting for solutions and came across Multi-Threading. I have known about this for some time, but have yet to dive into the practice. My program seemed to need more speed and smoother operation so I took a stab at it. The below code in its complete form is the result, however it crashes and throws errors. Clearly I have not used Threading as it was intended. Using it in simpler functions works fine and I feel I have the grasp. That is if i want my program to pointlessly run counters.
I don't know what to do next in my steps for getting this task done, and figure I am combining several different methods into a mush of dead program. I could really use some help getting back on track with this. All comments welcome and thank you for checking out my code.
Form1 Code
Public Class Form1
'Obj Array
Public Shared objDevice As New List(Of kDevice)
'Thread Array for each Obj
Public Shared thread() As System.Threading.Thread
Private Sub ipRefresh(objID, itemPos)
Dim objDev As kDevice = objID
If My.Computer.Network.Ping(objDev.kIP) Then
objDev.kStatus = "Online"
objDev.kPings = 0
Else
objDev.kPings += 1
End If
If objDev.kPings >= 8 Then
objDev.kStatus = "Offline"
objDev.kPings = 0
ListView1.Items(itemPos).BackColor = Color.Red
End If
Dim str(4) As String
Dim itm As ListViewItem
str(0) = objDev.kName
str(1) = objDev.kIP
str(2) = objDev.kStatus
str(3) = objDev.kPings
itm = New ListViewItem(str)
ListView1.Items(itemPos) = itm
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.CheckForIllegalCrossThreadCalls = False
' Adding ListView Columns
ListView1.Columns.Add("Device", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("IP Address", 150, HorizontalAlignment.Left)
ListView1.Columns.Add("Status", 60, HorizontalAlignment.Left)
ListView1.Columns.Add("Pings", 60, HorizontalAlignment.Left)
Dim ipList As New List(Of String)
Dim nameList As New List(Of String)
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("kDevices.csv")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
Dim rowP As Integer = 1
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim cellP As Integer = 0
Dim nTemp As String = ""
For Each currentField As String In currentRow
Select Case cellP
Case 0
nameList.Add(currentField.Replace("""", ""))
Case 1
ipList.Add(currentField.Replace("""", ""))
End Select
cellP += 1
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
rowP += 1
End While
End Using
Dim nameLAR As String() = nameList.ToArray
Dim ipLAR As String() = ipList.ToArray
ReDim Preserve thread(nameLAR.Length)
For i As Integer = 0 To nameLAR.Length - 1
Dim newDevice As New kDevice
Dim objNum = i
objDevice.Add(newDevice)
newDevice.kName = nameLAR(i)
newDevice.kIP = ipLAR(i)
If My.Computer.Network.Ping(newDevice.kIP) Then
newDevice.kStatus = "Online"
Else
newDevice.kStatus = "Loading"
End If
Dim str(4) As String
Dim itm As ListViewItem
str(0) = newDevice.kName
str(1) = newDevice.kIP
str(2) = newDevice.kStatus
str(3) = newDevice.kPings
itm = New ListViewItem(str)
If newDevice.kStatus = "Loading" Then
itm.BackColor = Color.Yellow
End If
ListView1.Items.Add(itm)
thread(objNum) = New System.Threading.Thread(Sub() Me.ipRefresh(objDevice(objNum), objNum))
Next
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
For i As Integer = 0 To objDevice.Count - 1
thread(i).Start()
Next
End Sub
End Class
kDevice Class
Public Class kDevice
Private strkName As String
Private strkIP As String
Private strkStatus As String
Private strkLastStatus As String
Private strkPings As Integer = 0
Public Property kName As String
Get
Return strkName
End Get
Set(value As String)
strkName = value
End Set
End Property
Public Property kIP As String
Get
Return strkIP
End Get
Set(value As String)
strkIP = value
End Set
End Property
Public Property kStatus As String
Get
Return strkStatus
End Get
Set(value As String)
strkStatus = value
End Set
End Property
Public Property kPings As Integer
Get
Return strkPings
End Get
Set(value As Integer)
strkPings = value
End Set
End Property
End Class
The Error / Crash on Line 32 of my code which is when it tries to pass the update to the ListView Item
An unhandled exception of type 'System.ArgumentException'
occurred in Microsoft.VisualBasic.dll
Additional information: InvalidArgument=Value of '18'
is not valid for 'index'.
or
An unhandled exception of type 'System.NullReferenceException'
occurred in Microsoft.VisualBasic.dll
Additional information: Object reference not set to an instance
of an object.
If my code does not make sense, or at lease the idea of what I was trying to make it do, please let me know and I will explain whichever parts are unclear. Again thank you for looking over my issue.
Just a possible issue I noticed:
Dim str(4) As String
Dim itm As ListViewItem
str(0) = newDevice.kName
str(1) = newDevice.kIP
str(2) = newDevice.kStatus
str(3) = newDevice.kPings
itm = New ListViewItem(str)
If newDevice.kStatus = "Loading" Then
itm.BackColor = Color.Yellow
End If
ListView1.Items.Add(itm)
In this bit here, you declare str(4) which would be 5 possible indexes (remember it starts at zero), where you should have 4 (str(3)) . I don't think this is the whole issue, but just a small bit you should probably fix. You also may want to look into other ways to update the listview without setting
Me.CheckForIllegalCrossThreadCalls = False
Here's an awesome guide that helped me when I did my first multi threaded application: http://checktechno.blogspot.com/2012/11/multi-thread-for-newbies.html
I am using an httpWebRequest in my windows app to download files from a webserver (sURL), to a local folder (fileDestination) as such:
Public Function DownloadFile(ByVal sURL As String, _
ByVal fileDestination As String, _
ByVal WebRequestType As String) As Boolean
Dim URLReq As HttpWebRequest
Dim URLRes As HttpWebResponse
Dim FileStreamer As FileStream
Dim bBuffer(999) As Byte
Dim iBytesRead As Integer
Dim folderDestination As String
Dim sChunks As Stream
Try
FileStreamer = New FileStream(fileDestination, FileMode.Create)
URLReq = WebRequest.Create(sURL)
URLRes = URLReq.GetResponse 'Error occurs here!!
sChunks = URLReq.GetResponse.GetResponseStream
DownloadProgressBar.Value = 0
DownloadProgressBar.Maximum = URLRes.ContentLength
Do
iBytesRead = sChunks.Read(bBuffer, 0, 1000)
FileStreamer.Write(bBuffer, 0, iBytesRead)
Loop Until iBytesRead = 0
sChunks.Close()
FileStreamer.Close()
URLRes.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
This works fine for the first few files. But then it starts giving the following error on the URLReq.GetResponse line:
"operation has timed out"
Anyone know what could be causing this?
If you're targeting the 1.1 framework and are running multiple concurrent requests try setting System.Net.ServicePointManager.DefaultConnectionLimit
The timeout is set to 10000 milliseconds (or 10 seconds). Is that long enough for the roundtrip to the web server?
The MSDN Documentation says the default is 100 seconds (100000 ms) is there any reason you changed that default?