Parallel Programming
C# and RabbitMQ PubSub Example
Before you run the following C# code, run the below docker code to have a RabbitMQ applicaton locally.
docker run -d –hostname my-rabbit –name some-rabbit -p 8080:15672 -p 5672:5672 rabbitmq:3-management
After run Docker RabbitMQ container, you can reach from http://localhost:8080/ as shown in following picture.
C# Convert from Event-based asynchronous pattern(EAP) to Task-based asynchronous pattern(TAP) with Redis PubSub
C# Convert from Event-based Asynchronous Pattern(EAP) to Task-based asynchronous pattern(TAP) Example
This example show how to convert Event-based Asynchronous Pattern(EAP) to Task-based asynchronous pattern(TAP). I hope you like it 🙂
Calling Synchronous Methods Asynchronously with different Patterns
The .NET Framework enables you to call any method asynchronously. Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.
There are several patterns to call a synchronous method asynchronously as shown below.
1- BeginInvoke and EndInvoke
2- WaitHandle
3- Polling
4- Callback
BeginInvoke and EndInvoke Pattern
As you see that first message written in console is worked in main thread (ThreadID is 1), But, DoWork() method is called asynchronously, so that, second message is worked on different thread (ThreadID is 3).
DoWork() method returns int value and without parameters, so that, BeginInvoke method shows two parameters(callback, @object) as shown in Figure-2
Notice that EndInvoke() method takes asyncResult variable returned by BeginInvoke() method and it also returns int value because of Func delegate in Figure-3.