Resolved Invoke tasks repeatedly but only if previous task completed

fakeNoose

Member
Joined
Sep 19, 2019
Messages
10
Programming Experience
Beginner
Hey Everyone

I'm using the below to find all children classes of an abstract base class and then instantiate each of them and add that instance to a list.

What I'm wanting to be able to do is loop through that list of instances and run a Task that is part of the abstract base class for each instance every second, but I only want to run that task if the previous task run a second ago is completed. I've seen others do something similar using Func<Task> but I have no idea how they implemented that.

Is this something that is possible to do and if so how should I go about doing it?

Thank you in advance!!

C#:
public static List<ConsumableBase> Instances = new List<ConsumableBase>();
public static async void Manage()
{
    IEnumerable<Type> _classes = GetChildrenOfType(typeof(ConsumableBase));
    foreach (Type _class in _classes)
    {
        ConsumableBase _obj = (ConsumableBase) InstantiateType(_class);
        Instances.Add(_obj);
    }
}
private static IEnumerable<Type> GetChildrenOfType(Type _type)
{
    var _classes = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(p => _type.IsAssignableFrom(p));

    return _classes;
}

private static object InstantiateType(Type _type)
{
    var _ctors = _type.GetConstructors(BindingFlags.Public);
    var _inst = _ctors[0].Invoke(new object[] { });

    return _inst;
}
 
The first thing that comes to mind is this sort of thing:
C#:
private Task currentTask;

public void StartNewTask()
{
    if (currentTask?.IsCompleted == true)
    {
        currentTask = Task.Run(DoSomething);
    }
}

public void DoSomething()
{
    // ...
}
You can then call StartNewTask wherever and whenever you want, e.g. from the event handler for a Timer that is invoked every second.
 
Actually, I just realised that my code isn't quite right. That should be:
C#:
if (currentTask?.IsCompleted != false)
The first time around, currentTask will be null and thus currentTask?.IsCompleted will be also be null. If that expression is null or true then you want to start a new task.
 
Back
Top Bottom