Alex
Alex

Reputation: 11137

why isn't user-control class access not safe from another thread?

As the title says , why isn't user-control class access not safe from another thread? I heard that there is a way to enable cross-thread access and am thinking of doing so.. Any thought why i shouldn't ?

Upvotes: 2

Views: 1229

Answers (3)

Cody Gray
Cody Gray

Reputation: 244772

Allowing access to a WinForms control from another thread (i.e., one that it was not created on) could lead to deadlocks and race conditions. Two threads that are running simultaneously, both trying to update the same control, could end up waiting on each other to finish before they are able to do anything. (See MSDN.) WinForms protects you from these kinds of hidden bugs.

If you want, you can easily instruct the control's thread that you want it to update the control using the BeginInvoke method and passing it a delegate:

myUserControl.BeginInvoke(myUserControl.PaintItBlack);

This will execute the specified delegate asynchronously on the thread that created the control, ensuring safe access.

Upvotes: 3

Aaron McIver
Aaron McIver

Reputation: 24713

UserControl instances have thread affinity with the "UI thread" which will require marshaling back and forth as you attempt to move from potential worker thread to UI thread.

In addition the thread safety component is something different entirely, as all member variables for instance will need to be synchronized in case the single UserControl instance is being shared across multiple threads, therefore potentially being accessed as well.

Could this be done? In theory yes...should it be done? Not necessarily. I would revisit your design and question why you need this behavior in the UserControl. Separation of concerns should surface and perhaps you can get the time consuming tasks out of the UserControl, therefore alleviating you from this burden.

Upvotes: 3

Evan Mulawski
Evan Mulawski

Reputation: 55334

Take a look at this:

http://msdn.microsoft.com/en-us/library/ms171728.aspx

Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way.

Upvotes: 7

Related Questions