I met this interesting question :
If I have an event and 2 long calculated function subscribed to this event :
It seems its work synchronously : ( method 2 will have to wait to method 1 to finish)
public class A
{
public event Action f;
public void Start()
{
f();
}
}
void Main()
{
A a = new A();
a.f += Work1;
a.f += Work2;
a.Start();
}
public void Work1()
{
"w1 started".Dump();
decimal k = 0;
for(decimal i = 0; i < (99999999); i++)
{
k++;
}
"w1 ended".Dump();
}
public void Work2()
{
"w2 started".Dump();
decimal k = 0;
for(decimal i = 0; i < 99999999; i++)
{
k++;
}
"w2 ended".Dump();
}
Result :
Question :
IMHO , it has an invocation list and THAT'S is the reason why it run synchronously.
How can I make it run A-synchronously
?
The event itself will always run it subscribers one after another.
But you can always e.g. wrap your method with a Task
void Main()
{
A a = new A();
a.f += () => Task.Factory.StartNew(Work1);
a.f += () => Task.Factory.StartNew(Work2);
a.Start();
}
or use some other kind of multithreading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With