private protected Functions used for Event Handler in C-Sharp (code execution hangs in an Event Handler)



Question: How do you make "private protected void Function()" in C# call an async function? When I prifix the function as below the code throws an error:

private async Task myCallBackFunction(){

//Do Something

}

When I try to bind the function above to the Event Handler, an Error is thrown
  For Example: 

   myDeligate.SomeFunction += myCallBackFunction; //Error is thrown here.


Answer: You should be very carefull calling async functions in the Event Handler in C#, you might introduce a really Nasty Bug that you won't be able to reproduce
               in your Development or Staging Enviroment.
               However, if you really want to call an Async Function in a Protected Function that is registered as an Event Handler then you should prifix the protected  function with an "async" and make it a "void". See example below:

Example:

protected async void myCallBackFunction(){

//Some Code here
var myVariable = await callAsyncFuntion().ConfigureAwait(false);

//Do some interesting stuff here

//Do Something
return; //This is very important as you do not want the execution to hang in the Event Handler. This can be a very costly mistake, always remember to return.
}

The code above should resolve your error, this will still tell the Compiler that the function does not return anything, it is just suppose to do something then just return nothing.

If you want to route to another View based on the result then you should look into ways to call the FrontEnd Javascript so that the Javascript can call View Function on the Server side. This will help you resolve some issues around Dependency Injection since the Application might lose state when code execution enters the Envent handler.