0

I need to raise an event without blocking the calling method, what is the way to do it?

1) Start a task and raise the event from within the task? :

//Body of listener function above
if (EventFound)
   Task.Factory.StartNew(() => 
   {
     SendEvent();
   });

2) Start a task from within the eventhandler:

public void OnEventRaised(....)
{

    Task.Factory.StartNew(() => 
    {
    //Do lengthy stuff here
    });

}

Does either block the calling function?

Azriel H
  • 45
  • 4

2 Answers2

1

Neither of your examples blocks the caller.

In your first example the caller creates a new thread and invokes all subscribers sequentially (if there are more than one). In the second option the subscriber creates a thread, so each one will have it's own thread.

Please keep in mind that both options will crash the application if any of the event handlers fail.

You can get more relevant information from here: Raising events asynchronously

Community
  • 1
  • 1
Dmytro Zakharov
  • 1,016
  • 8
  • 13
0

You can use Async Await keywords http://www.codeproject.com/Tips/591586/Asynchronous-Programming-in-Csharp-using-async

Giri
  • 126
  • 1
  • 6