Is it possible to have multiple threads drawing on the same canvas?
Canvas Drawing should be done ONLY in the PAINT EVENT of the canvas
Suggest you create a PICTURE, and have your threads draw to that, then have the PAINT EVENT just update from that picture object
There are couple of thoughts for this:
You can not use unmodified threads to draw into a canvas because you’ll get the Thread Accessing UI Exception. However, you should be able to use the Task Thread (see examples) to get that to work. Depending on how you had expected to use the thread this might be very hard to implement.
But assuming you can get one working you should be able to get two working. If these threads cooperate with one another then you’ll have more work to do get them synchronized.
Thanks. I looked into this TaskThread example but it is rather complicated though
Bob… doesn’t this violate TWO tenets of Xojo?
- Do not attempt to update the UI from a thread
- Do not attempt to update a Canvas from outside of its Paint Event
Maybe, the following method is good enough:
- Create a Picture
- Modify the Picture Object in the Threads
- Create an “Invalidate”-Timer with Period=0 and Mode=Off and in the Action Event just write the Canvas.Invalidate command
- In the Paint Event of the Canvas, draw the Picture into the Canvas
Now at the end of each Thread, you just do a “Invalidate”-Timer.Mode = Single
[i]I do not know if an issue may arise if 2 or more Threads manipulate the picture at the same time, but you could put these Code Pieces in the Threads into Try-Catch Blocks and prepare your code for these situations.
Or you draw in layers.[/i]
Take a look at Examples/Graphics and Multimedia/DrawingWithThreads.
As Dave suggests above, it draws to an offscreen picture that is then updated in the Canvas Paint event handler.
[quote=278972:@Dave S]Bob… doesn’t this violate TWO tenets of Xojo?
Do not attempt to update the UI from a thread
Do not attempt to update a Canvas from outside of its Paint Event[/quote]
Right, but you could use the Task UI thread to create the data and/or image and use the Timer event to put the proper image in place and invalidate the canvas object. It’s hokey but it would work but who knows if it’s fast enough for the OP.
Bob, I doubt that speed is a real issue, as everyone knows that using multiple threads is slower than a single thread, or even faster, no threads. There must be some other reason for wanting to draw from multiple threads.
Hard to say without knowing more. I think many don’t realize how much drawing you can really do in a Paint event. So they think they have do something extra.