Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ C # asynchronous delegates     - Oracle Standby Redo Log experiment (Database)

- Spring REST Exception Handling (Programming)

- Redis is installed and set up Ubuntu 14.04 from the environment under the main ssdb (Server)

- Struts2 study notes -Valuestack (value stack) and OGNL expression (Programming)

- Linux SSH commands (Linux)

- Linux Network Programming - raw socket Example: sending a UDP packet (Programming)

- AWR Report (Database)

- CentOS7 iptables (Linux)

- Mac Docker deploy development environment (Server)

- Shell script on the variables with double quotation marks grep small problem (Programming)

- Oracle Database asynchronous IO cause slow query response (Database)

- Lenovo E431 notebook CentOS system is installed wireless network card driver (Linux)

- Broadcom transplanted to OpenWrt summary (Programming)

- Mounting kit under Fedora Linux (Linux)

- Use Android Studio and Gradle packaged multi-version APK (Programming)

- Construction CA certificate using OpenSSL command line (Server)

- Oracle background processes daemons (Database)

- On the Web application attack techniques Common (Linux)

- Linux_Logo - output color ANSI Linux distributions logo command-line tool (Linux)

- Linux smart small switch rfkill (Linux)

 
         
  C # asynchronous delegates
     
  Add Date : 2017-08-31      
         
       
         
  In C #, a delegate type is type-safe, object-oriented function pointer. When we have a delegate by delegate keyword defines the type, the compiler will generate a delegate type three methods: Invoke, BeginInvoke and EndInvoke.

For example, the following delegate type, you can view the three methods generated by the compiler ILSpy.

private delegate int NumberAdd (int a, int b);

Synchronous execution delegate instance

Using delegate applications, the most common is through Invoke () method in a synchronized manner delegate instance. That is, the calling thread will delegate to wait until the call is completed delegate.

Let's look at an example of a synchronous execution delegate, delegate instance in numberAdd by Sleep (3000) simulates a time-consuming operation:

NumberAdd numberAdd = (a, b) => {
    Thread.Sleep (3000);
    Console.WriteLine ( "----> NumberAdd () on thread is {0}", Thread.CurrentThread.ManagedThreadId);
    Console.WriteLine ( "----> start to calc {0} + {1}", a, b);
    Console.WriteLine ( "----> test result is {0}", a + b);
    return a + b;
};

Console.WriteLine ( "main thread (id: {0}) invoke numberAdd function", Thread.CurrentThread.ManagedThreadId);
// Int result = numberAdd (2, 5);
int result = numberAdd.Invoke (2, 5);
Console.WriteLine ( "main thread (id: {0}) get the result: {1}", Thread.CurrentThread.ManagedThreadId, result);
Output code for the next, it can be seen from the results, the main thread execution delegate instance process will be blocked until the delegate instance is executed, the main thread will continue.

In many applications, a method may be executed for a long time, such as loading a large file, or perform a time-consuming database operations. If we use a synchronous manner to perform the method, the main thread will remain blocked until the completion of the implementation of this method, the application performance is not appropriate, it affects the user experience. In this case, you can consider calling a method performed by asynchronous delegate.

BeginInvoke () and EndInvoke ()

Before you begin introduces asynchronous execution of the commission, first look BeginInvoke () and EndInvoke () method, combined with the above type NumberAdd commissioned to analyze the parameters of these two methods and return types.

.method public hidebysig newslot virtual
    instance class [mscorlib] System.IAsyncResult BeginInvoke (
        int32 a,
        int32 b,
        class [mscorlib] System.AsyncCallback callback,
        object 'object'
    ) Runtime managed
{
} // End of method NumberAdd :: BeginInvoke
BeginInvoke () method is used to start an asynchronous call, it has the same parameters as the delegate type; this example is int32 a and int32 b
BeginInvoke () method has two optional parameters:
AsyncCallback delegate can specify the method (callback function) to be called when the asynchronous call is completed by this parameter
User-defined object that can pass information to the callback method
BeginInvoke () method returns immediately after the call, without waiting for the completion of the implementation commission; that does not block the calling thread can continue execution
BeginInvoke () returns the implement IAsyncResult interface object, the object can be used to monitor the progress of the asynchronous call; get results in the preparation of a method call, you can pass it on to EndInvoke () method
.method public hidebysig newslot virtual
    instance int32 EndInvoke (
        class [mscorlib] System.IAsyncResult result
    ) Runtime managed
{
} // End of method NumberAdd :: EndInvoke
EndInvoke method return type is the return type of the delegate type, this example is int32
(Return BeginInvoke () method of the result) is only one parameter EndInvoke implement IAsyncResult interface, combined with the parameter EndInvoke () method to get the results of the asynchronous call
After calling BeginInvoke () method, you can call EndInvoke () method at any time, if the asynchronous call has not been completed, EndInvoke () method will always block the calling thread until the asynchronous call to complete before allowing the calling thread execution
Asynchronous execution delegate instance

Introduced BeginInvoke () and EndInvoke () methods, see an asynchronous method call examples.

Console.WriteLine ( "main thread (id: {0}) invoke numberAdd function", Thread.CurrentThread.ManagedThreadId);
IAsyncResult iAsyncResult = numberAdd.BeginInvoke (2, 5, null, null);
Console.WriteLine ( "main thread (id: {0}) can do something after BeginInvoke", Thread.CurrentThread.ManagedThreadId);
for (int i = 0; i < 5; i ++)
    Console.WriteLine ( "......");
Console.WriteLine ( "main thread (id: {0}) wait at EndInvoke", Thread.CurrentThread.ManagedThreadId);
// Main thread will call EndInvoke at blocking known until the completion of the implementation of asynchronous call
int result = numberAdd.EndInvoke (iAsyncResult);
Console.WriteLine ( "main thread get the result: {0}", result);
The output of the code, you can see that in fact asynchronous delegate uses a new thread to execute numberAdd instance, so that the main thread will not be blocked after BeginInvoke can proceed; but when the main thread execution to EndInvoke, due to the asynchronous call has not completed, the main thread will be blocked in the EndInvoke place.

In fact, this case is still a big problem, the main thread will still be blocked. Below a little bit of improvement, by polling the state view the asynchronous call.

Polling asynchronous call state

In IAsyncResult interface by implementing this interface instance IsCompleted property, it can detect whether the asynchronous operation has been completed indicating if the operation was completed True, otherwise False

A brief look at the members of the IAsyncResult:

AsyncState: Get user-defined objects can be used as argument to the callback function, the callback function from the calling thread want to pass information
AsyncWaitHandle: Get used to wait for an asynchronous operation to complete WaitHandle
CompletedSynchronously: Gets a value that indicates whether the asynchronous operation completed synchronously
IsCompleted: Gets a Boolean value that indicates whether the asynchronous operation has been completed
So, you can use the code to get the state IsCompleted asynchronous operations:

Console.WriteLine ( "main invoke numberAdd function");
IAsyncResult iAsyncResult = numberAdd.BeginInvoke (2, 5, null, null);
while (iAsyncResult.IsCompleted! = true)
{
    Console.WriteLine ( "main thread can do something after BeginInvoke");
    Console.WriteLine ( "......");
    Thread.Sleep (500);
}
int result = numberAdd.EndInvoke (iAsyncResult);
Console.WriteLine ( "main thread get the result: {0}", result);
Similarly, IAsyncResult instance there is a AsyncWaitHandle type attribute, this attribute can be achieved through more flexible wait logic.

This property returns a WaitHandle instance type, the method by WaitOne this instance you can call synchronous and asynchronous thread between the methods:

Console.WriteLine ( "main invoke numberAdd function");
IAsyncResult iAsyncResult = numberAdd.BeginInvoke (2, 5, null, null);
while (! iAsyncResult.AsyncWaitHandle.WaitOne (500))
{
    Console.WriteLine ( "main thread can do something after BeginInvoke");
    Console.WriteLine ( "......");
}
int result = numberAdd.EndInvoke (iAsyncResult);
Console.WriteLine ( "main thread get the result: {0}", result);
Use AsyncCallback

To detect the execution status of an asynchronous method call by polling the way is not a good way to achieve the asynchronous method calls, the best way to achieve that by AsyncCallback delegate to specify a callback function. So that after the completion of the asynchronous method, asynchronous thread will proactively notify the calling thread.

The following examples provide a callback function NumberAddCompleted, when the asynchronous method execution is completed, the callback function is called.

Note: The callback function needs to be a delegate instance, before you can call EndInvoke method to get the result of an asynchronous method execution, so the example uses "System.Runtime.Remoting.Messaging" namespace AsyncResult type to get delegate instance.

Console.WriteLine ( "main invoke numberAdd function");
IAsyncResult iAsyncResult = numberAdd.BeginInvoke (2, 5, NumberAddCompleted, "this is a msg from main");
for (int i = 0; i < 5; i ++)
{
    Console.WriteLine ( "main thread can do something after BeginInvoke");
    Console.WriteLine ( "......");
    Thread.Sleep (500);
}

private static void NumberAddCompleted (IAsyncResult iAsyncResult)
{
    Console.WriteLine ( "numberAdd function complete, run callback function");
    AsyncResult asyncResult = (AsyncResult) iAsyncResult;
   
    Console.WriteLine (asyncResult.AsyncState as string);
// Get delegate instance by instance type AsyncResult
    NumberAdd numberAdd = (NumberAdd) asyncResult.AsyncDelegate;
    int result = numberAdd.EndInvoke (iAsyncResult);
    Console.WriteLine ( "main thread get the result: {0}", result);
    
}
to sum up

This article describes the C # compiler generated delegate type BeginInvoke () and EndInvoke () method. Through some simple example demonstrates how BeginInvoke () and EndInvoke () method to complete the asynchronous method call.

When we need to perform time-consuming operation, we do not want the calling thread is blocked, you can consider using asynchronous delegates. Examples of asynchronous execution through the commission can be seen, in fact, the underlying asynchronous delegate uses multithreading (direct use of thread pool threads). Therefore, the use of asynchronous delegate place, we can also be achieved by a multi-threaded approach.
     
         
       
         
  More:      
 
- Linux kernel RCU (Read Copy Update) lock Brief - prequel (Linux)
- RabbitMQ tutorial examples: the Hello RabbitMQ World Java realization (Linux)
- The oh-my-zsh into true my zsh (Linux)
- To read the Linux ext3 / ext4 format partitions under Windows system software (Linux)
- Nginx1.8 version upgrade method AMH4.2 Free manually compile (Server)
- Single-node Hadoop installation notes distributed pseudo & (Server)
- Linux_Logo - output color ANSI Linux distributions logo command-line tool (Linux)
- Android memory optimization of the memory cache (Linux)
- Install Debian Linux with R on the Android system (Linux)
- SELinux security permissions HTTP + PHP service changes (Server)
- The Linux C truncate function clears the file notes (Programming)
- Zabbix installation and configuration process (Server)
- TCP protocol flaw incomplete records (Linux)
- MySQL view (Database)
- Database start listening TNS-12537, TNS-12560 error (Database)
- MySQL IO SSD attempt at optimization (Database)
- Android Scroller call mechanism and the relationship of computeScroll (Programming)
- To establish a secure and reliable Linux operating system (Linux)
- Java Graphics2D Paint (Programming)
- CentOS 6.6 permanent method to modify the DNS address (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.