0

I have a textbox in my page named LinkURL. I'm trying to create Uri with its Text value. And use the Uri for BitmapImage. So the user can see the image while typing the URL.

But my UI freezes and application stops running. I'd like to use it for preview image.

public void LoadImage(object sender, TextChangedEventArgs e)
{
    Uri uri = null;
    Dispatcher.BeginInvoke(new Action(delegate
    {
        uri = new Uri(this.LinkURL.Text);
        WebClient wc = new WebClient();
        wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
        wc.OpenReadAsync(uri, wc);
    }));
}

private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.StreamSource = e.Result;
    this.Preview.Source = bi;
}  

I tried these but didn't work.

UI freezes and gives me System.Reflection.TargetInvocationException or ArgumentNullException.

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
neuraminidase7
  • 486
  • 2
  • 7
  • 19
  • "Didn't work" is not much to go on. Can you be more specific? – Koen Feb 09 '14 at 00:31
  • 2
    You forgot to call EndInit – Thomas Levesque Feb 09 '14 at 01:44
  • 2
    And your BeginInvoke call is useless; the code will still be executed on the UI thread. Just using OpenReadAsync is usually enough to avoid blocking the UI. (I say "usually" because OpenReadAsync does some things synchronously, like DNS resolution) – Thomas Levesque Feb 09 '14 at 01:45
  • To add to @ThomasLevesque's comments, `Dispatcher.BeginInvoke` would not help to avoid the UI blocking, if `DNS resolution` happens synchronously inside `OpenReadAsync`, it will just postpone it. Check [this](http://stackoverflow.com/q/21007112/1768303) for a solution. – noseratio Feb 09 '14 at 02:48

0 Answers0