0

I have a list view that is populated with the location of some html files on the local disk. When an the list is double clicked it takes the first selected item and loads that file location to the web browser control. I have fiddled around with async/await to try and get the UI free while the file loads to the web browser but it still hangs the UI.

   private async void ListView1_DoubleClick(object sender, EventArgs e)
    {
        await LoadPage(listView1.SelectedItems[0].Text);
    }

    private async Task LoadPage(string uri)
    {

        Uri myURI = new Uri(uri);
        await Task.Factory.StartNew(()=>webBrowser1.Navigate(myURI),CancellationToken.None,TaskCreationOptions.LongRunning,TaskScheduler.Default);

    }

Code works, the UI is still hanging though.

1 Answers1

0

Task.Factory.StartNew with TaskScheduler.Default runs your code in a thread-pool thread. This is not supposed to happen for code that manipulates UI elements, like the WebBrowser control. You could add the line bellow before Application.Run, to protect yourself from such mistakes.

Control.CheckForIllegalCrossThreadCalls = true;

Related link: Why are we allowed to modify the form title from a thread pool thread?

I don't think you can do much about the WebBrowser control slowing down your UI. Maybe hiding it initially, ans showing in again on DocumentCompleted?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104