I want enqueue a list of tasks and then perform on certain event. Code:
internal class MyClass
{
private Queue<Task> m_taskQueue;
protected MyClass()
{
m_taskQueue = new Queue<Task>();
}
public delegate bool Task(object[] args);
public void EnqueueTask(Task task)
{
m_taskQueue.Enqueue(task);
}
public virtual bool Save()
{
// save by processing work queue
while (m_taskQueue.Count > 0)
{
var task = m_taskQueue.Dequeue();
var workItemResult = task.Invoke();
if (!workItemResult)
{
// give up on a failure
m_taskQueue.Clear();
return false;
}
}
return true;
}
}
Each delegate task may have their own list of parameters: Task(object[] args). My question is how to pass the parameter to each task for the task queue?
Okay, now we have a bit more information, it sounds like your
EnqueueTaskmethod should actually look like this:Right?
For starters I would avoid using the name
Task, which is already part of the core of .NET 4 and will become very prominent in .NET 5. As Joshua said, you’ve basically got aFunc<object[], bool>.Next, you could keep two lists – one for the delegates and one for the values, but it’s easier just to keep a
Queue<Func<bool>>like this:Then the rest of your code will actually work “as is”. The lambda expression there will capture
valuesandtask, so when you invoke theFunc<bool>, it will supply those values to the original delegate.