Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run .net event Asynchronously?

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 :

enter image description here

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 ?

like image 356
Royi Namir Avatar asked Feb 19 '23 12:02

Royi Namir


1 Answers

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.

like image 160
sloth Avatar answered Feb 22 '23 02:02

sloth