C#创建函数队列 [英] C# creating function queue
问题描述
我已经写了一个类的QueueManager:
I have written a class called QueueManager:
class QueueManager
{
Queue functionsQueue;
public bool IsEmpty
{
get
{
if (functionsQueue.Count == 0)
return true;
else
return false;
}
}
public QueueManager()
{
functionsQueue = new Queue();
}
public bool Contains(Action action)
{
if (functionsQueue.Contains(action))
return true;
else
return false;
}
public Action Pop()
{
return functionsQueue.Dequeue() as Action;
}
public void Add(Action function)
{
functionsQueue.Enqueue(function);
}
public void Add(Func<CacheObject,Boolean> function)
{
functionsQueue.Enqueue(function);
}
当我创建这个类的一个实例,并调用添加方法,它工作正常,不带参数的功能,例如: functionQueue.Add(方法); ,但有一个参数和返回值的方法调用(在我的案件类类别作为参数,和布尔的返回值),例如functionQueue.Add(方法2(classObject))时;它没有编制,我缺少什么?
and when I create an instance of this class and call Add method it works fine for functions with no arguments, for example: functionQueue.Add(Method); , but when calling on methods that have an argument and return value(in my case ClassType as argument, and Boolean as return value), for example functionQueue.Add(Method2(classObject)); it does not compile, what am I missing?
推荐答案
由于与 functionQueue.Add(方法2(classObject))
你排队你的电话,而不是结果调用本身。
Because with functionQueue.Add(Method2(classObject))
you queue the result of your call, not the call itself.
要排队的方法与参数,你应该修改添加
原型来接受参数(和他们一起储存与委托)。作为替代方案,你可以使用lambda表达式:
To enqueue a method with parameters you should change the Add
prototype to accept parameters (and store them together with the delegate). As alternative you can use lambdas:
functionQueue.Add(() => Method2(classObject));
(那么你的第二个重载添加
是没用的,你总是可以排队一个动作
你给所有的瓶盖内参数)。
(then your second overload of Add
is useless, you can always queue an Action
where you give all the parameters inside the closure).
更新
这种类型的队列的一个例子是内部的WinForms,调度的从其他线程的方法比主线程与一个的方法队列的(看的拆卸 Control.MarshaledInvoke做
)。跳过同步和场景中,它保持了 System.Collections.Queue
,其中每个条目 ThreadMethodEntry
(以持有需要使用的结构数据)。
Update
An example of a queue of this type is inside WinForms, dispatching of methods from other threads than the main thread is done with a method queue (look at the disassembly of Control.MarshaledInvoke
). Skipping synchronization and contexts it keeps a System.Collections.Queue
where each entry is ThreadMethodEntry
(a structure used to hold needed data).
这篇关于C#创建函数队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!