【问题标题】:How to add a custom message pump supporting parameters?如何添加自定义消息泵支持参数?
【发布时间】:2014-03-25 16:39:27
【问题描述】:

这与这个问题有关: How to create custom message pump?

我基本上需要相同的消息泵,除了它还需要能够支持输入参数。上述问题的答案仅支持不接受参数的 Action() 委托。我希望能够将参数传递给我的操作。这是无参数版本:

public class MessagePump
{
    private BlockingCollection<Action> actions = new BlockingCollection<Action>();

    public void Run() //you may want to restrict this so that only one caller from one thread is running messages
    {
        foreach (var action in actions.GetConsumingEnumerable())
            action();
    }

    public void AddWork(Action action)
    {
        actions.Add(action);
    }

    public void Stop()
    {
        actions.CompleteAdding();
    }
}

这样做的正确方法是什么?我正在考虑让 BlockingCollection 存储一个自定义类而不是 Action,假设称为 ActionWithParameter,如下所示:

class ActionWithParameter
{
   Action action;
   object parameter;
}

但它看起来很笨重,而且在获取动作时我还需要一些 switch 语句来确定参数是什么类型,以便能够调用动作(参数)。另外,如果我想支持多个参数怎么办?那我应该使用object[] parameters 吗?肯定有更好的解决方案吗?

【问题讨论】:

    标签: c# multithreading action blockingcollection message-pump


    【解决方案1】:

    在委托线程中找到了解决方案: How to store delegates in a List

    我可以使用以下语法将函数和参数存储在 Action 类型中。:

    actions.Add(new Action(() => MyFunction(myParameter)));
    

    这也解决了我多参数的问题。

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2012-03-19
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多