Fire .net event Asynchronously?

I met this interesting question:

If I have an event and two long calculated functions subscribed to this event:

It seems that its operation is synchronous: (method 2 will have to wait for method 1 to complete)

public class A { public event Action f; public void Start() { f(); } } void Main() { A a = new A(); af += Work1; af += 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:

enter image description here

Question:

IMHO, it has a call list and THAT'S - the reason it runs synchronously.

How can I run it A-synchronously ?

+4
source share
1 answer

The event itself will always launch subscribers one by one.

But you can always, for example. wrap your Task method

 void Main() { A a = new A(); af += () => Task.Factory.StartNew(Work1); af += () => Task.Factory.StartNew(Work2); a.Start(); } 

or use a different type of multithreading.

+8
source

All Articles