ForeUI offers a powerful behavior engine, which allows you to define complex interaction in an elegant way for any GUI element on the screen. Sometimes you may want to run multiple tasks parallelly, which is also called “multi-threading” in the software industry. For example, assume we have a button, and we want to move it on right-down direction and enlarge it at the same time. Is it possible to do so in ForeUI? The answer is positive, that’s why I write this post 🙂
First let’s create a single-thread version for the example, so you can later compare it with the multi-threading version. The example only contains one button element (Button_1) and its behavior is defined as below:
There are two loops in the event handler for “Element Clicked” event: one for moving and one for resizing the button. I designedly use different looping parameters for them, so we have good reason that not to merge them into one loop. Since it is a single-thread version, it can only do the moving and resizing in sequence, like this:
Now lets try to make the multi-threading. The basic of the trick is that, the event triggering is not a blocking call. That means, when you trigger two events in order, the second event will not wait for the execution of event handler for the first event. As a non-blocking call, triggering an event takes almost no time, so the two events seems to be triggered at the same time, and their event handlers seems to be launched together.
So I changed the behavior for Button_1 as below. I added two “Element_Clicked” events to Button_1 and they will do moving and resizing accordingly. There are two warnings (highlighted with yellow) since we place the same event twice in one element. We know what we are doing, so just ignore these warnings.
Since the two loops are placed in different event handlers, they will be launched at (almost) the same time, thus you will see they are executed parallelly:
If you’d like to place the behavior definition in custom event handler, you can modify the example like this: (download this plot file)
If you don’t want to use global custom event, you can define it as the private event for Button_1, like this: (download this plot file)
The three examples above will work in the same way, you can choose the one you like when you want to do multi-threading in ForeUI.