为什么我的事件处理程序停止执行事件引发程序?

时间:2018-12-06 00:07:39

标签: c# multithreading events .net-4.0 task

经过广泛搜索,我仍然对有关事件,任务和线程的一些基本编程概念感到困惑。请注意,这是针对.Net 4.0,没有等待/异步。

这很可能是重复的,但如果找不到,我找不到。我已将问题嵌入代码的“程序”部分中,以免破坏阅读流程。

事件发布者:

public class Publisher  
{
    public event EventHandler<EventArgs> ProgressChanged;

    public void Run(int iterations)
    {
        for (int i = 0; i < iterations; i++)
        {
            Console.WriteLine("Will fire event in iteration {0} in a second", i);
            Thread.Sleep(1000);
            OnProgressChanged();
        }
    }

    private void OnProgressChanged()
    {
        EventHandler<EventArgs> handler = ProgressChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty); // raise event
        }
    }
}

事件监听器:

public class Listener
{
    public void HandleProgressChanged(object sender, EventArgs e)
    {
        Console.WriteLine("event handled, waiting 2 seconds to continue");
        Thread.Sleep(2000);
    }
}

程序:

class Program
{
    static void Main(string[] args)
    {
        Publisher p = new Publisher();
        Listener c = new Listener();
        p.ProgressChanged += c.HandleProgressChanged;

        Console.WriteLine(" --the regular way--");
        p.Run(2);

        // QUESTION 1:
        // execution of Run halts until its subscribers have processed the event. Why?
        // my intuition tells me the Run method should just do it's thing, uninterrupted
        // and any listeners should pick it up without affecting the publisher.
        // This is obviously too naive an understanding, but why?
        // Is this because the event raising method
        // waits for its subscribers to finish processing the event?
        // if so, why?

        Console.WriteLine("--the tasks way--");
        Task.Factory.StartNew(() => p.Run(2)); // used a lambda to allow passing a parameter to Run

        // QUESTION 2:
        // execution of Run still halts until its subscribers have processed the event. Why?
        // it was assigned it's own task, so why does it still wait for it's listeners to finish? 

        // What I would like is to have the publisher run it's thing,
        // and have listeners respond to its events without disrupting the publisher

        Console.ReadKey();

    }
}

0 个答案:

没有答案