Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ C # asynchronous delegates     - CentOS 7 virt-manager can not connect a local hypervisor (Linux)

- Role Object of registerNatives () method (Programming)

- OpenNMS compile under Linux (Server)

- Three binary tree traversal (recursive, non-recursive traversal and Morris) (Programming)

- CentOS 6.x and CentOS7 install MPlayer (Linux)

- Linux Getting Started tutorial: build your own Vim (Linux)

- Interesting example of Linux Sort command (Linux)

- OpenSUSE / Linux network configuration (Linux)

- grep command usage (Linux)

- Install Ubuntu 14.04 and Windows 8 / 8.1 dual-boot in UEFI mode (Linux)

- linux firewall configuration (Linux)

- Linux server security - the web server configuration (Linux)

- Linux System Getting Started Learning: DeVeDe installed on Linux to create a video DVD (Linux)

- Linux-based Heartbeat high availability configuration httpd service (Server)

- Virtualization and IT cooperation (Linux)

- Cross server / client backup command: rsync use (Server)

- Arrow keys, backspace key garbled in Python-2.7.5 Interactive Mode under CentOS 5.8 (Linux)

- GoldenGate update is missing (Database)

- CentOS yum source deployment (Linux)

- Debian users to install FFmpeg 2.2.2 (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:      
 
- Use CutyCapt to convert HTML pages to png images on Linux (Linux)
- Linux Getting Started tutorial: Borrow Windows fonts in Ubuntu 14.10 (Linux)
- Build RPM package uses Docker mirror (Linux)
- CentOS 6.5 Linux System Customization and Packaging Quick Implementation Script (Linux)
- Github with .gitignore ignore specified file (Linux)
- Java data structures - the single linked list LinkedList linear table (Programming)
- CKEditor + SWFUpload achieve a more powerful editor (Linux)
- How to create a remote (Linux)
- 10 Codes of good practice PHP (Programming)
- Vim useful plugin: EasyGrep (Linux)
- OpenCV 3.0 + Python 2.7 installation and testing under Ubuntu 14.04 (Linux)
- Rails project prepared some tips small experience (Linux)
- Cacti monitoring service Nginx (Linux)
- Linux server network penetration testing (Linux)
- How to use GRUB2 files directly from the hard disk to run ISO (Linux)
- Oracle 12c In-Memory Study (Database)
- Ubuntu and derivative system users how to install Pinta 1.5 (Linux)
- Java, hashcode, equals and == (Programming)
- Install Git on CentOS (Linux)
- Docker commonly used commands Description (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.