0

I'm learning on how to use Async and Await. I wrote this code to fetch a website and write it on a RichTextBox in every one second. The problem is, if there's a network slowdown, the fetching of the page slows down too and the UI freezes briefly. This is the code:

Imports System.Net
Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer1.Start()
    End Sub

    Private Async Function FetchData(uri As String) As Task(Of String)
        Using wb As New WebClient
            Dim stream As New StreamReader(wb.OpenRead(uri))
            Return Await stream.ReadToEndAsync
        End Using
    End Function

    Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        RichTextBox1.Text = Await FetchData("http://someurl")
    End Sub
End Class
JFetz2191
  • 139
  • 1
  • 2
  • 10
  • I would suggest to use `IProgress(Of T)` like shown in [this](https://stackoverflow.com/a/30303129/2882256) example. – Alex B. Nov 08 '17 at 08:34
  • I guess the problem is because the next timer tick occurs before the current fetching process finishes. A new task might start to fetch the website while the previous tasks are yet to complete. – Moayad Hani Abu Rmilah Nov 08 '17 at 08:44
  • Notice that updating `RichTextBox1.Text` will happened synchronously and will freeze you UI if "someurl" return big amount of text. – Fabio Nov 08 '17 at 08:57

0 Answers0