Abdallah Alsayed asked:
…but how to use thread and cross-thread invocation?
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
Basically, in your second, non-UI thread, you should work only with data representing graphics. The main, UI thread, should only render the same data. You need to synchronize this data between threads. To render data, override the method
System.Windows.Control.OnPaint
of some control. It can be a custom control. To fight flicker effectively, use double buffering (please see control's options). When the data is modified in the second thread (call it "scenario thread"), simply invoke some delegate which calls
Control.Invalidate
on the rendering control. It will push
WM_PAINT
Windows message, so your
OnPaint
handler will be called. With updated data. This way, your animation will be pushed onto the rendering system.
You can also call one of the
Invalidate
methods with parameters, to render just the part of the scene and improve performance on the parts of the scene where the data was not modified by the animation (you will need to specify a
Rectangle
or
Region
for update. If you sequentially quickly invalidate several times with different subsets of the scene points, the involved regions will be merged before they reach the rendering.
This all gives you pretty good performance.
But even better performance can be achieved with WPF, because it is based on fast DirectX.
Please also see my past answers:
Drawing Lines between mdi child forms[
^],
capture the drawing on a panel[
^],
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[
^].
—SA