I have a permanent object with some event. Is it possible to make this object active throughout the life of the application. Suppose that an object and an event look like this:

var myObject = new MyObject(); myObject.CustomEvent += _myEvent; private void _myEvent(object sender, CustomEvent e) { using (var db = new DbContext()) { db.MyEntity.Add(e.Property); db.SaveChanges(); } } 

I tried to put it in the Startup class and the Application_Start method. Also tried to add to HostingEnvironment.QueueBackgroundWorkItem . As I understand it, the object is destroyed everywhere and the event does not occur. Thanks for the help!

  • How do you think, who dies earlier, _myEvent, the class to which belongs _myEvent (along with it) or myObject, without sending an event? - nick_n_a
  • one
    There is no difference where the object is stored. And the "active" objects in your understanding - also does not exist. You have an error in the code that raises the event. - Pavel Mayorov
  • Honestly, I do not know. But as a fact the event does not occur, and if we create an object, for example, in the controller, then everything is ok. - loqie
  • one
    And why are you sure that the event is caused at all? - Pavel Mayorov
  • one
    Admit already, who is for the external code, what kind of event and why you are processing it. Because in the current form, the code is completely working. - Pavel Mayorov

1 answer 1

The object remains alive (active) as long as it is reachable from one of the roots of the garbage collection. Roots of it

  • Variables on the stack are local variables of the functions that are currently being executed, and their callers.
  • GCHandle-s - links to managed objects assigned for transfer to unmanaged code
  • Static fields

Make myObject a static field - and it will live forever.