richzilla
richzilla

Reputation: 42082

Why do certain properties on a Control have a higher priority

Leading on from this question, Why do certain properties of a control (the Label class for instance) cause a call to Control.Handle but others dont.

I can only assume then, that changes to the forecolor of the label are only picked up when the window needs to be refreshed. If this is the case, then what makes the Text property so important that it needs to immediately inform the window when its value has changed?

Upvotes: 1

Views: 94

Answers (1)

Hans Passant
Hans Passant

Reputation: 942518

It does not have anything to do with "priority", it is simply related to the way the control works. The MSDN Library documents the four members of the Control class that are thread-safe: InvokeRequired, BeginInvoke, Invoke and CreateGraphics. But there are a few corner cases where code can be thread-safe even though it uses another member.

For example, the Text property of most controls are safe to read but not to write. A simple side-effect of the property value being stored in a backing field, an optimization that avoids having to make the expensive winapi call. Works when you read the property, you simply get the backing field value. But not when you write because that requires setting the backing field and updating the native window. The latter operating trips the exception.

And properties like BackColor and ForeColor are often thread-safe. Because they are simple, their setters just update a backing field and call Invalidate(). Which is a safe function when its invalidateChildren argument is false, it merely updates the "dirty rectangle" of the window. The one that, later, causes the Paint event to fire on the UI thread.

Which was one optimization too many. It is thread-safe in that it isn't going to cause your program to fall over with a deadlock or a nasty undiagnosable exception. It however doesn't provide a guarantee that the user can actually see the updated color. If your worker thread updates BackColor and the UI thread is busy painting the window at the same time then it will be using the stale value of BackColor but still mark the window as valid when painting completes. In effect never actually changing the background color. It won't take effect until the next time the control repaints itself, that can take a long while. A standard mishap in programs that use threading, called a threading race. This one is pretty benign. But like all threading races very hard to diagnose, this doesn't go wrong often enough.

Upvotes: 4

Related Questions