Say I use
wb as webclient
wb.downloadstring(url)
Say 40 seconds have passed. I want wb to just give up. How to do so?
Printable View
Say I use
wb as webclient
wb.downloadstring(url)
Say 40 seconds have passed. I want wb to just give up. How to do so?
As far as I'm aware, you can't. You could call DownloadStringAsync instead and use a Timer to call CancelAsync after a specific period. Otherwise, if you want to actually set a timeout on the operation, you would have to use an HttpWebRequest, which has a Timeout property.
I see. That httpwebrequest seems to be better than webclient isn't it?
Also is there any chance that webclient will just hang forever?
Given that the WebClient uses a WebRequest internally, it's not better. The WebClient is simple to use and is therefore the better choice for simple scenarios. The WebRequest class gives you finer-grained control so it's the better choice for situations where you need finer-grained control.I've never researched that before but I did have a quick look around when I read your question and I saw no specific indication that that is not the case.
I set my program to just terminate the thread.
Yea but using async will be too complicated. I suppose, I can do async and then provide a call back function using lamda expression, and then use sleep and then has a loop to check whether it's still busy or not. I'll just have to think about that one. Actually if webclient has a default time out, it'll be fine.
I think I'll follow your advice and use that async thingy with a special function. So create myDownloadStringFunction :)
Using an async method will not be complicated unless you make it so, which that description does.
E.g.vb.net Code:
Imports System.Net Public Class Form1 Private WithEvents client As WebClient Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If Me.client Is Nothing Then Me.client = New WebClient End If If Not Me.client.IsBusy Then Me.client.DownloadStringAsync(New Uri(Me.TextBox1.Text)) End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If Me.client IsNot Nothing AndAlso Me.client.IsBusy Then Me.client.CancelAsync() End If End Sub Private Sub client_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs) Handles client.DownloadStringCompleted If Not e.Cancelled Then Me.DisplayDownloadedString(e.Result) End If End Sub Private Sub DisplayDownloadedString(ByVal text As String) If Me.InvokeRequired Then Me.Invoke(New Action(Of String)(AddressOf DisplayDownloadedString), text) Else MessageBox.Show(text) End If End Sub End Class
I know it's not jmcilheney. It's just that I want to use async for synchronous operation (because I already do the multi threading part)
So I will have to do
async
wait till time out or finish
done
And if it's timed out, what I will do is terminate the thread anyway. It's okay.