Simple multi-threading issue

104 views Asked by At

I have a class called Movement which moves a picture box (guy on the left) on my form to a random position when it's Lead method gets executed. I also have a method which moves another picture box (dark guy on the right) called SetMrShadowToMove. These two picture boxes are suppose to move at the same time and arrive at the random point (one point for both picture boxes) at the same time.

enter image description here

For now, these methods use a timer to move the picture boxes, but my main intention was to have a loop which runs until the picture box's coordinates meet the random point picked while using Thread.Sleep to delay the process and make an animation of it.

To do that, I need to run both methods on different threads, so my UI thread doesn't get frozen and these methods would run at the same time.

My problem is that I don't know how to run these methods on different threads, and also don't know how to access the picture boxes on the other threads (it seems that this has something to do with invoking and stuff!).

What is the best way to solve this problem?

1

There are 1 answers

4
Nick Otten On

The best way (in my opinion) is by using a background worker.

those things can do there calculations in the background. If you you want to update the interface after that you can use there report progress event to invoke your main (interface) thread and redraw the screen. You can also the work complete even if you want to have a event of the background worker as a final even (for example if mister shadow is 'destroyed' or something).

I don't know your code of mister shadow so I don't have any direct example code for you. But a full example about how to use a background worker can be found on msdn here. I hope this will help you.