Creating threads that can interact with form elements, an easy alternative
Written by: daveI’ve been working on a personal project (more for learning than anything else) in C# where the user can perform a search and preview images as thumbnails on a button then select an image they want. I wanted images to start showing up as soon as the user began typing. The time it takes to shrink just 9 full sized photos to a thumbnail image is large enough that performing the search can become unbearable. Naturally I decided to solve the problem using threads, but ran into a brick wall when an exception was thrown – apparently, developers are unable to change form elements from different threads.
The exception had a link I followed that gave information on how to overcome this issue. While the article was not super easy to follow, I was able to manage. I noticed a lot of people posted questions on forums on how to overcome this error, so I got to thinking and came up with what I think is an easier alternative.
My basic setup is as follows:
- The buttons are first created on the form.
- A timer is started.
- Threads are created that shrink images to thumbnail sizes for being displayed on the button.
- A class ThreadedQ is created in which it stores a thread number, a reference to a button, a reference to the image to be shrinked, and a reference to Q (defined next)
- The calling form has a variable, List
Q, defined. - As threads complete, they push ThreadedQ objects onto Q.
- Whenever the timer ticks, it checks Q for items; when one is found, it maps the newly created thumbnail to the button it references.
- When all threads have completed, the timer stops.
While this setup may not be as good as what the original tutorial proposed, I think it may be easier for beginners to follow.
