Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c# - Draw many controls quickly using async?

I have a windows form with many controls on it (mainly text boxes and buttons). Every time I chance the size of the form I change the size and position of the controls so that they are nicely distributed over the form. The problem is that when I change the size of the form it takes up to half a second to redraw all the controls. How can I speed this up?

I have used System.Diagnostics.Stopwatch to time my code and I think that the part that is taking a long time is actually the drawing of the controls on screen (since the math I am doing is completed in less than a millisecond). I have also optimized it so controls are only redrawn when necessary.

One idea I had was to use async functions to draw the controls using several different threads but I don't know much about how forms draw their controls so I don't know if this is possible. This question seems to indicate it's not possible to draw controls from another thread. (I have also never used async programming before and am not sure how I would do it so if this is possible any pointers would be appreciated).

My main questions are:

  • Is it possible to use async programming to do this?
  • Is there another/better way?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Only the UI-thread can update the UI. Therefore multitasking cannot be used to speed up drawing to the UI.

Try setting DoubleBuffered = true; in the form after InitializeComponent();. Sometimes this helps. This setting is often used to reduce flicker.

Are you trying to distribute the controls programmatically? You can use the Anchor property to have winforms do this automatically for you. There is also a FlowLayoutPanel and a TableLayoutPanel. These panels are very helpful for automatic layouts. Even the SplitContainer can be useful for layouting.

If you are making changes to the UI, you can also try to suspend winforms' layouting. This prevents winforms from doing unnecessary calculations and drawing.

SuspendLayout();
try {
    // TODO: Your positioning and sizing logic
} finally {
    ResumeLayout();
}

The try-finally ensures that ResumeLayout runs even in case of an exception, or when you leave the code block with return.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...