Creating an image control in a seperated thread
-
Hi. I have a wpf app that have a stack panel that i would like to populate with images that i'm downloading from a website. to avoid getting the UI from freezing while downloading the images i created another thread and in that thread downloaded the images and tried to create the image controls. but i'm getting this exception: "The calling thread must be STA, because many UI components require this." Here is the thread code:
new Thread(delegate() { string searchUrl = siteAlgorithm.BuildSearchExpression(searchKeyWords); searcherObj.Clear(); searcherObj.LoadNewPage(siteAlgorithm.ExtractSearchResults(myWebClient.DownloadSiteToString(searchUrl))); MemoryStream stream; Image img = new Image(); // ---> Exception Thrown System.Windows.Media.Imaging.BitmapImage bitImg; foreach (SearchResult item in searcherObj.FirstPage.resultItems) { stream = new MemoryStream(myWebClient.DownloadData(item.imageUrl)); bitImg = new System.Windows.Media.Imaging.BitmapImage(); bitImg.BeginInit(); bitImg.StreamSource = stream; bitImg.EndInit(); img.Source = bitImg; Gui.AddSearchResultItem(img, item.info, item.uri); } } ).Start();
-
Hi. I have a wpf app that have a stack panel that i would like to populate with images that i'm downloading from a website. to avoid getting the UI from freezing while downloading the images i created another thread and in that thread downloaded the images and tried to create the image controls. but i'm getting this exception: "The calling thread must be STA, because many UI components require this." Here is the thread code:
new Thread(delegate() { string searchUrl = siteAlgorithm.BuildSearchExpression(searchKeyWords); searcherObj.Clear(); searcherObj.LoadNewPage(siteAlgorithm.ExtractSearchResults(myWebClient.DownloadSiteToString(searchUrl))); MemoryStream stream; Image img = new Image(); // ---> Exception Thrown System.Windows.Media.Imaging.BitmapImage bitImg; foreach (SearchResult item in searcherObj.FirstPage.resultItems) { stream = new MemoryStream(myWebClient.DownloadData(item.imageUrl)); bitImg = new System.Windows.Media.Imaging.BitmapImage(); bitImg.BeginInit(); bitImg.StreamSource = stream; bitImg.EndInit(); img.Source = bitImg; Gui.AddSearchResultItem(img, item.info, item.uri); } } ).Start();
You can't create controls from another thread. You CAN use the background worker class to download them, and it's work finished delegate runs on the main thread, as does the progress event, so you can use those to put your image into your page.
Christian Graus Driven to the arms of OSX by Vista. Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.