在完成事件A后触发事件B.

时间:2013-08-16 15:53:12

标签: c# events methods

对不起,如果标题没有意义。

我有两件事。事件A,B和I具有方法M1和M2。 M1订阅了活动A. 当方法M1触发时,它触发了引发事件B的方法M2。

这是方案:

A raised
  M1 fired
    M2 fired
      B raised
        ----
        ----
      B ended
    M2 ended
  M1 ended
A ended

我想要的是等到A结束并加注B.因为当A工作时,B的订户无法完成他们的工作。

这就是我想要的。

A raised
  M1 fired
    somehow specify to fire M2 right after A finished
  M1 ended
A ended
M2 fired
   B raised
      ----
      ----
   B ended
M2 ended

这样做的有效方法是什么?

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

M1开始运行Task的新ThreadM2。那样M1将能够完成执行,然后M2稍后启动。如果存在阻止M2M1完成之前执行任何操作的同步机制,则执行顺序将如您所示。

示例:

public class Foo
{
    public event Action A;
    public event Action B;

    public Foo()
    {
        A += M1;
    }

    private object key = new object();
    private void M1()
    {
        lock (key)
        {
            Task.Run(() => M2());
        }
    }
    private void M2()
    {
        lock (key)
        {
            if (B != null)
                B();
        }
    }
}

答案 1 :(得分:0)

这样的事情怎么样:

public class EventThing
{
    public event Action A;
    public event Action B;

    public EventThing()
    {
        A += () =>
        {
            Action next = M1();
            if (next != null)
                next();
        };
    }
    public void FireA()
    {
        var AHandlers = A;
        if (AHAndlers != null)
        {
            foreach (Action action in (AHAndlers as MulticastDelegate).GetInvocationList().Reverse())
                action();
        }
    }
    private Action M1()
    {
        Console.WriteLine("Running M1");
        return M2;
    }
    private void M2()
    {
        Console.WriteLine("Running M2");
        if (B != null)
            B();
    }
}

static void Main(string[] args)
{
    var eventThing = new EventThing();
    eventThing.A += () => Console.WriteLine("Performing A");
    eventThing.B += () => Console.WriteLine("Performing B");
    eventThing.FireA();
    Console.ReadLine();
}

输出:

Performing A
Running M1 
Running M2
Performing B