C# Events and Thread Safety

前端 未结 15 1148
甜味超标
甜味超标 2020-11-22 06:00

UPDATE

As of C# 6, the answer to this question is:

SomeEvent?.Invoke(this, e);

I frequently hear/read the fo

15条回答
  •  别那么骄傲
    2020-11-22 06:11

    I've been using this design pattern to ensure that event handlers aren't executed after they're unsubscribed. It's working pretty well so far, although I haven't tried any performance profiling.

    private readonly object eventMutex = new object();
    
    private event EventHandler _onEvent = null;
    
    public event EventHandler OnEvent
    {
      add
      {
        lock(eventMutex)
        {
          _onEvent += value;
        }
      }
    
      remove
      {
        lock(eventMutex)
        {
          _onEvent -= value;
        }
      }
    
    }
    
    private void HandleEvent(EventArgs args)
    {
      lock(eventMutex)
      {
        if (_onEvent != null)
          _onEvent(args);
      }
    }
    

    I'm mostly working with Mono for Android these days, and Android doesn't seem to like it when you try to update a View after its Activity has been sent to the background.

提交回复
热议问题