После тщательного поиска я все еще не понимаю некоторые основные концепции программирования, касающиеся событий, задач и потоков.Обратите внимание, что это для .Net 4.0, нет await / async.
Это может быть дубликатом, но если это так, я не нашел его.Я встроил свои вопросы в программную часть кода, чтобы не нарушать поток чтения.
издатель событий:
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();
}
}