Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I lock 'event'?

Tags:

c#

events

locking

should I lock event in the following case:

event foo;

thread A: will call foo += handler;

thread B: will call foo -= handler;

should I lock foo?

like image 691
Benny Avatar asked Feb 05 '10 07:02

Benny


People also ask

What is event lock?

Event locking allows a multithreaded event broker to categorize incoming alerts based on the values of specified alert fields and then to process them within a category one at a time in the order that they were sent to the ObjectServer.

What does Time Lock Do Studio One?

Time Lock Select this option to keep the Event from being moved to a different time position within the Track.

How do you unlock tracks in Cubase 10?

The events are locked. This is indicated by a padlock symbol. To unlock an event, select the event and select Edit > Unlock.


1 Answers

Locking on foo is a bad idea, because the value will change each time. You should lock on a variable which doesn't change:

private readonly object eventLock = new object();
private EventHandler fooHandler;

public event EventHandler Foo
{
    add
    {
        lock (eventLock)
        {
            fooHandler += value;
        }
    }
    remove
    {
        lock (eventLock)
        {
            fooHandler -= value;
        }
    }
}

private void OnFoo(EventArgs e)
{
    EventHandler handler;
    lock (eventLock)
    {
        handler = fooHandler;
    }
    if (handler != null)
    {
        handler(this, e);
    }
}

Note that if you use a field-like event, like this:

public event EventHandler Foo;

then you'll automatically get a "lock(this)" on add/remove, although you'd have to manually add it when fetching the handler before calling it (assuming you want to make sure you read the most recently written value). Personally I'm not a fan of locking on "this", but you may not mind - and it certainly makes for simpler code.

like image 80
Jon Skeet Avatar answered Sep 29 '22 23:09

Jon Skeet