Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ C # asynchronous delegates     - ORA-28000 the account is locked fault simulation (Database)

- Quick Install software RAID on Linux (Linux)

- Using PHP MySQL library (Programming)

- PL / SQL -> UTL_FILE use presentation package (Database)

- Ubuntu Live CD by updating Grub resume boot the Boot Menu (Linux)

- Disk Management LVM (Linux)

- Java is simple to read and write HDFS Demo (Programming)

- How to install Ubuntu applications Device 7 (Linux)

- Debian SSD ext4 4K aligned (Linux)

- Python2.7.7 source code analysis (Programming)

- Linux network security backdoor technology and advanced skill practice (Linux)

- CentOS / RedHat system partition essential requirements and partition scheme (Linux)

- Android using SVG vector graphics to create cool animation effects (Programming)

- Linux System shutdown procedures (Linux)

- ORA-00020: No more process state objects available (Database)

- CentOS modify yum update source (Linux)

- Deb package installation method under ubuntu (Linux)

- Httpclient4.4 of principle (Http execution context) (Programming)

- 127.0.0.1 and localhost difference (Server)

- High-performance JavaScript loaded and executed (Programming)

 
         
  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 development environment to build and use the directory structure and file --Linux (Linux)
- Bash job control (Linux)
- Ubuntu 14.04 virtual machine switching desktop environments (Linux)
- Graphical development environment to build Android under Ubuntu 11.04 (Linux)
- PLSQL Developer synchronization table tools (Database)
- CentOS 6.5 using Virtualenv under development environment to build Python3 (Linux)
- MongoDB configuration in Ubuntu 14.04 (Database)
- KUbuntu / Ubuntu 14.04 (downgrade) installed SVN 1.7 (Linux)
- Distributed transaction management Spring declarative transactions (Programming)
- NIC configuration parameters under Linux (Linux)
- secureCRT remote login Linux must first open the connection protocol (Linux)
- PostgreSQL-- run Supervisord on Docker in Ubuntu (Database)
- Linux automatically install service components and optimize the kernel parameters (Linux)
- CV: Linux command displays the progress of the run command (Linux)
- Four levels of intrusion on Linux server and counter-measures (Linux)
- Ubuntu 14.04 install Sublime Text 3 plug and use SublimeClang (Linux)
- Development environment to build MEAN In Ubuntu 15.10 (Server)
- CentOS 7 repair MBR and GRUB (Linux)
- Linux compiler of GCC (Linux)
- C # Future: Tracking null reference (Programming)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.