0

I want to create object that does some job, after job is done and some time has passed it destroys itself. I have written something, but don't know if it will work as I want it to work. I'm using MVC structure in my project, .NET Core 2.1

I made class:

public class DestroableBackroundWorker : IDestroableBackroundWorker
{       
    public int Quantity { get; set; }
    public int Successful { get; set; }
    public int Waiting { get; set; }
    public int Unsuccessful { get; set; }
    public bool Done { get; set; }
    public string Output { get; set; }
    public string ID { get; set; }

    public DestroableBackroundWorker (string jsonobject, string ID)
    {
        this.ID = ID;            
        Task.Run(() => Working(jsonobject));
        Task.Delay(3600000).ContinueWith(t => destroyme());
    }

    private void Working(string jsonobject)
    {        
        try
        {
            //does work here, updates parameters of itself, to be able to see progress
            Done = true;
            Task.Delay(120000).ContinueWith(t => destroyme());                
        }
        catch
        {
            Done = true;
            Task.Delay(120000).ContinueWith(t => destroyme());
        }
    }        

    public void destroyme()
    {
        Project.Controllers.API.BackgroundUploads.Remove(this);
    }
}

I also have this list in my API Controler:

public static List<IDestroableBackroundWorker> BackgroundUploads = new List<IDestroableBackroundWorker>();

I initiate object from API endpoint Like So:

string ID = Guid.NewGuid().ToString();
BackgroundUploads.Add(new DestroableBackroundWorker(info, ID));
return Json(ID);

If I want to Check progress I do this:

foreach (IDestroableBackroundWorker Worker in BackgroundUploads)
{
   if (Worker.ID == ID) {
      var Responce = new { All = Worker.Quantity, Success = Worker.successful, Unsuccess = Worker.unsuccessful };
      return Json(Responce);
   }
}
return Json(false);

I want to destroy that object, 2 minutes after work is done, or 1hour afrer object was created, will this work ok?, I tested it works as intended, it removes itself from BackgroundUploads List. I also noticed that after it deletes itself from that List, it still does work, if it has not finished it yet.

My question Consists of two parts:

  • is this okay?, if work is done and then it deletes itself from list, is that object gone ? I mean will it not use any memory or space ?
  • how to remove it even if it still does some kind of work, not to remove pointer, but also make so that that object uses no more memory, space, processor, stops doing any work, and is gone.

3 Answers 3

3

Remember what the purpose of a garbage collector is; it is to free you from the burden of having to worry about whether the object is still taking up memory or not. So don't worry about it!

Let the GC do its work. It will manage object lifetimes for you. When your program is no longer able to access the object because ever reference to it is no longer in known-to-be-alive memory, the object's memory will be reclaimed at at time of the GC's choosing in accordance with its policies.

Each process has multiple terabytes of address space. Don't worry about ensuring that a couple dozen bytes are freed as soon as possible. Those dozen bytes being freed a few seconds later will not make the difference between success and failure.

6
  • Thanks, for answering first part of the question ! @EricLippert Apr 22, 2020 at 18:17
  • @EmilisVadopalas: I answered both parts of your question. The answer to the first part is don't worry about lifetime, let the GC deal with it when the GC deals with it, and the answer to the second part is don't worry about the burden of 100 bytes when you literally have 8000000000000 bytes of address space available. Apr 22, 2020 at 18:28
  • 2
    @EmilisVadopalas: If your question is really "I started a background task that I want to cancel before it is done, how do I do so safely?'", that's a different question. Pass a cancellation token into the task, and check it periodically as the task runs. Apr 22, 2020 at 18:30
  • @EmilisVadopalas: Let me make an analogy. Suppose you have a to do list: mow the lawn, weed the garden, pick up groceries. You give your child the to-do list and she starts weeding the garden. Your question is "if I burn the to-do list does she stop weeding the garden?" The question of how to manage the memory associated with the task and how to deal with cancelling a task in the middle of its operation are completely different. Suppose you burn that list; do the tools get put away? Is the mower left running? Apr 22, 2020 at 19:00
  • @EmilisVadopalas: Writing asynchronous workflows that can be safely cancelled has nothing whatsoever to do with managing the memory associated with the task list. Make sure that is very clear in your mind. Writing a workflow that supports cancellation is not a memory management problem. It's about safely shutting down work that is in progress where stopping it prematurely has consequences, and that needs to be designed and tested. Apr 22, 2020 at 19:02
0

An object doesn't "know" whether there are references to it. If an object could internally decide to somehow destroy or nullify itself out of existence, bad things would happen.

Imagine this scenario - you've got a variable, x, that refers to an instance of some object and calls its methods:

x.DoSomething();
x.DoSomethingElse();

...and then suddenly, right in the middle of that, the object removes itself from memory. What would happen to the existing variable that refers to it? Would it be as if some invisible process mysteriously set x to null?

An object can be responsible for doing all sorts of things, but determining whether or not it itself continues to exist in memory isn't one of them.

Sometimes an object will internally reference resources that aren't affected by garbage collection. For example, garbage collection doesn't close an opened file stream. In those cases you would implement IDisposable and calling the Dispose method should release those resources. (That's not automatic. If you write a class that implements IDisposable you would have to actually write the code in or called by the Dispose method to release resources.)

But even then, that's the object internally managing resources it uses. Regardless of what the Dispose method does, an object can't make references to itself disappear.

0

many misunderstood my question, so probably I expressed it badly, but what I wanted to know is how to remove that object from list while also, stopping any work it is doing, @EricLippert pointed out that if the work is already done and I remove it from list I don't need to worry about anything else. And If I want to stop work I need to use cancellation token, so I edited my class like this:

public class DestroableBackroundWorker : IDestroableBackroundWorker
{       
   public int Quantity { get; set; }
   public int Successful { get; set; }
   public int Waiting { get; set; }
   public int Unsuccessful { get; set; }
   public bool Done { get; set; }
   public string Output { get; set; }
   public string ID { get; set; }

   CancellationTokenSource cts = new CancellationTokenSource();

   public DestroableBackroundWorker (string jsonobject, string ID)
   {
      this.ID = ID;            
      Task.Run(() => Working(jsonobject, cts.Token));
      Task.Delay(3600000).ContinueWith(t => destroyme());
   }

   private void Working(string jsonobject, CancellationToken cancellationToken)
   {        
      try
      {
         //place this at appropriate place/places, where can be stopped safely             
         cancellationToken.ThrowIfCancellationRequested();             

         //does work here, updates parameters of itself, to be able to see progress
         Done = true;
         Task.Delay(120000).ContinueWith(t => destroyme());                
      }
      catch
      {
         Done = true;
         Task.Delay(120000).ContinueWith(t => destroyme());
      }
   }        

   public void destroyme()
   {
      cts.Cancel();
      Project.Controllers.API.BackgroundUploads.Remove(this);

And I believe this solves it. So now When destroyme() method is called it also ends work.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.