Events and thread safety

1. How is implemented thread safe for instance events?

2. How is implemented thread safe for static events?

3. What are the problems with using by default thread synchronization locks?

4. Is it possible to make instance events thread safe for value types?

 

To ensure that only one thread calls add or remove method the C# compiler uses [MethodImplAttribute(MethodImplOptions.Synchronized)] attribute.

When this attribute is applied to an instance method the CLR uses object itself as the thread-synchronization lock.  

When this attribute is applied to a static method the CLR uses type object as the thread-synchronization lock.  

Using the same lock hurts performance and leads to deadlocks, when other threads wait the same lock.

It’s not possible to make instance events of value types thread safe because unboxed value type don’t have a lock object associated with them.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s