Delegates & Async Programming (.NETFramework)

May 1, 2020

Delegates have been available since the start of C# and actually offer us the first and easiest way into asynchronous programming. There is a keyword in C# named delegate which compiler will actually generate an entire class.

First assume this simple calling delegate and see the result:

The C# compiler based on delegate keyword generate a whole class that will be our type-safe means of having a function pointer. in fact somethingDelegate.Invoke() that happens behind the scenes when we have somethingDelegate().

Now we have an opportunity to look at something asynchronous.
So with the invoke method, we have some other helper methods as well. And this follows begin/end pattern for asynchronous processing. So tying BeginInvoke and EndInvoke together allows us to call a method, that will cause the method being referenced to be run asynchronously. So a background thread will take care of it, and we will continue our code on the main calling thread.

The BeginInvoke and EndInvoke are connected together through result (IAsyncResult). By the way this codes will not run in .NET Core check this article for more explanation. So now the result is:

As you can see in the output DoingSomething run in different thread.
Now it’s time to make it all set in right place:

As you see we call CallBack after delegate finished and we end call EndInvoke there, and result:

So what happened here? As you noticed no log for so something here. Why? because we are in UnitTest Method and test method will not know any thing about background thread here the test result will be Green even without waiting for Background thread. We have to wait for delegate to be completed. asyncResult.AsyncWaitHandle.WaitOne()

Now we have an expected result:

Also we have option to catch exceptions raised by delegate method in CallBack:

Leave a Reply:

Your email address will not be published. Required fields are marked *