The answer is most definitely yes. The reason is because accessing UI control state correctly involves a lot of work. You basically have to marshal a method call onto the UI thread to access a control properly. That marshaling operation requires sending a message to the UI thread via the message pump that contains a delegate reference. The UI thread will eventually pick it up and execute it. Since I have never timed this operation I cannnot say for sure how expensive it is, but I suspect it is a nontrivial amount of time. It has to be done this way because UI controls have thread affinity. That means they can only be accessed on the thread that created them. To marshal a delegate use the Control.Invoke
or Control.BeginInvoke
methods.
Fredrik already mentioned one really good workaround for avoiding the marshaling operation. Here is what it might look like in code.
public partial class YourForm : Form
{
// Make sure to mark this variable as volatile.
private volatile bool m_Checked;
private void YourForm_Load(object sender, EventArgs e)
{
m_Checked = YourCheckbox.Checked;
var thread = new Thread(
() =>
{
while (true)
{
// This read will come from main memory since the
// variable is marked as volatile.
bool value = m_Checked;
}
});
thread.Start();
}
private void YourCheckbox_CheckedChanged(object sender, EventArgs e)
{
// This write will be committed to main memory since the
// variable is marked as volatile.
m_Checked = YourCheckbox.Checked;
}
}