Penguin
Penguin

Reputation: 33

Stop Form Freeze When Downloading String From Website

In my application, I have a web client that is supposed to download a string from a website. It downloads quite a large amount of text, about 20 lines or so. However, when I download the text, the GUI freezes while downloading and then resumes after it's done downloading. How can I prevent this?

I am using Visual Basic 2010, .NET 4.0, Windows Forms, and Windows 7 x64.

Upvotes: 0

Views: 948

Answers (3)

I4V
I4V

Reputation: 35363

You can use Task Parallel Library for this

Task.Factory.StartNew(() =>
    {
        using (var wc = new WebClient())
        {
            return wc.DownloadString("http://www.google.com");
        }
    })
.ContinueWith((t,_)=>
    {
            textBox1.Text = t.Result;
    }, 
    null,
    TaskScheduler.FromCurrentSynchronizationContext());

PS: Although you can use this template for any method that doesn't have async version, WebClient.DownloadString do have one, so I would choose Karl Anderson's answer

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34844

Another alternative is to use DownloadStringAsync, this will fire the request from the UI thread, but it will not block the thread, because it is an asynchronous request. Here is an example of using DownloadStringAsync:

Public Class Form1
    Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
        '  Did the request go as planned (no cancellation or error)?
        If e.Cancelled = False AndAlso e.Error Is Nothing Then
            ' Do something with the result here
            'e.Result
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim wc As New WebClient

        AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded

        wc.DownloadStringAsync(New Uri("http://www.google.com"))
    End Sub
End Class

Upvotes: 0

Hyperboreus
Hyperboreus

Reputation: 32449

Do time intensive tasks in worker threads and not on the GUI thread. This will prevent the event loop from freezing.

Upvotes: 0

Related Questions