Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ C # asynchronous delegates     - Bash How to read a file line by line (Programming)

- Cacti monitoring service Nginx (Linux)

- Linux for enterprises to build a firewall (Linux)

- Let the router be your security barrier against external attack (Linux)

- To protect the temporary files for Linux security (Linux)

- JavaScript closures and the scope chain (Programming)

- Java reflection mechanism explained in detail and Method.invoke explanation (Programming)

- Android Studio Getting Started Hello World (Programming)

- View processes and threads under Linux (Linux)

- Through Oracle to help restore MySQL data problems (Database)

- Linux Monitoring Command (Linux)

- Share and show your code on GitHub (Linux)

- linux server security (Linux)

- How to protect your eyes automatically adjust the screen brightness on Linux (Linux)

- Windows and Ubuntu dual system, repair of two ways UEFI boot (Linux)

- How to find the available network adapter on Ubuntu (Linux)

- Safe learning through self-extracting package to achieve invasion (Linux)

- XenServer Virtual Machine Installation --- first ISO image file storage expansion (Linux)

- Ubuntu the ARP (arptables) (Linux)

- Install Ubuntu text editor KKEdit 0.2.10 (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:      
 
- Netcat Example (Linux)
- Compile and install GCC 4.8.1 + GDB 7.6.1 + Eclipse in CentOS 6.4 in (Linux)
- CentOS 7 source code to compile and install PHP5.6 Nginx1.7.9 and MySQL (LNMP build environment) (Server)
- Shell scripts get a snapshot of the page and generates thumbnails (Linux)
- Disable unnecessary services under Linux (Linux)
- Generators and iterators in Python (Programming)
- How to Start a Linux application running in the background using the terminal mode (Linux)
- Linux System Getting Started Tutorial: permission to permanently modify the USB device in Linux (Linux)
- Linux top command to get started (Linux)
- RHEL 7.1 compile and install Ganglia 3.7.1 (Server)
- Database Blob data type conversion String (Programming)
- OpenCV cvFindCornerSubPix () to find sub-pixel Corner (Programming)
- CentOS 6.4 installation environment to build Scrapy 0.22 (Linux)
- Using PPA to install the lightweight theme software HotShots 2.1.0 under Ubuntu (Linux)
- IronPython and C # to interact (Programming)
- Linux Troubleshooting: How to save the status of the SSH session is closed (Linux)
- Ubuntu install video conversion tool Selene (Linux)
- RPM package management tools under Linux (Linux)
- Use OpenSSL carried BASE64 encoding and decoding (Linux)
- BusyBox build root file system (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.