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.