Synchronizing raising of events and adding delegates to them

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mczard@poczta.onet.pl

    Synchronizing raising of events and adding delegates to them

    In my application events can be raised in one thread, but delegates
    can be added to the events from another thread. I wonder if I really
    have to synchronize the event raising and all += / -= operations.

    Do I have to write:

    lock ( source.NewInput ) {
    source.NewInput += this.NewInputHa ndler;
    }

    and

    protected virtual void OnNewInput(obje ct sender, NewInputEventAr gs e)
    {
    if (NewInput != null)
    {
    lock ( NewInput )
    {
    NewInput(this, e);
    }
    }
    }


    ???

    Without the locks my application works correctly, but I know this
    doesn't proof anything.

    I cannot find any info on the web, because word "event" has too many
    meanings.
  • mczard@poczta.onet.pl

    #2
    Re: Synchronizing raising of events and adding delegates to them

    On 14 Lut, 11:45, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
    Seehttp://pobox.com/~skeet/csharp/threads/lockchoice.shtm lfor a
    working pattern.
    Thanks for that comment, but seems that equally good, but more
    simple will be to write only:

    protected virtual OnSomeEvent(Eve ntArgs e)
    {
    SomeEventHandle r handler;
    lock (this)
    {
    handler = someEvent;
    }
    if (handler != null)
    {
    handler (this, e);
    }
    }

    Am I right? Locking of += and -= is already done with 'this',
    so why shouldn't I use it?

    Comment

    Working...