(Original) step by step to learn remoting 5: asynchronous operations

Source: Internet
Author: User
Tags time in milliseconds

Step by step remoting 5: asynchronous operations

It doesn't matter if you don't know what Asynchronization is. Let's look at the instance. It is the most profound understanding through the instance.
In remoting, we can use the following asynchronous methods:
1. normal asynchronous
2. asynchronous callback
3. Unidirectional Asynchronization
One by one, first we modify our remote object: Public int alongtimemethod (int A, int B, int time)
{
Console. writeline ("Asynchronous Method start ");
System. Threading. thread. Sleep (time );
Console. writeline ("End of Asynchronous Method ");
Return A + B;
}

In this method, two parameters are input, and two parameters are returned, indicating that the method is successfully executed. The method takes time in milliseconds. This is a long method.
If the method is called through asynchronous remote call, We need to note that the line output by this method is output on the server rather than the client. Therefore, to make the test simple, we are still using local objects. Before implementing Asynchronization, let's take a look at the synchronous call method. Why is this blocking? Because we have called the main thread of the method, we are waiting. Let's see the test: datetime dt = datetime. now;
Remoteobject. myobject APP = new remoteobject. myobject ();
Console. writeline (App. alongtimemethod (1, 2, 1000 ));
Method ();
Console. writeline ("used" + (timespan) (datetime. Now-Dt). totalseconds + "second ");
Console. Readline ();

Assuming that the method is the main thread method, it takes 3 seconds: Private Static void method ()
{
Console. writeline ("main thread method start ");
System. Threading. thread. Sleep (3000 );
Console. writeline ("main thread method ended ");
}

Now, run the program:

After 4 seconds, it indicates that the local machine has been waiting since the start of our method. The total used time = Local method + remote method. This is obviously unscientific for long-time method calls! We need to improve:

1. Normal Asynchronization:
First, add the delegate before the main method. The signature and return types are consistent with those of the Asynchronous Method. Private delegate int mydelegate (int A, int B, int time );

Write this in the main method: datetime dt = datetime. now;
Remoteobject. myobject APP = new remoteobject. myobject ();
Mydelegate MD = new mydelegate (App. alongtimemethod );
Iasyncresult IAR = md. begininvoke (1000, null, null );
Method ();
If (! IAR. iscompleted)
{
IAR. asyncwaithandle. waitone ();
}
Else
{
Console. writeline ("result is" + MD. endinvoke (IAR ));
}
Console. writeline ("used" + (timespan) (datetime. Now-Dt). totalseconds + "second ");
Console. Readline ();

Let's take a look at the execution result:

Now the total execution time is close to the execution time of the main thread, so the call method basically does not take up the time.
Analyze the code: IAR. asyncwaithandle. waitone (); is blocked and waits for the Asynchronous Method to complete. The code here will not be executed, because when the main method is complete, the asynchronous method has been iscompleted for a long time. If we modify the code: iasyncresult IAR = md. begininvoke (5000, null, null );

As you can see, after the main thread method ends, it is waiting for the Asynchronous Method to complete. The total time used is close to that of the Asynchronous Method: 5 seconds.

In actual use, the main thread often needs to get the result of the asynchronous method, that is, close to the above situation, after a small amount of work is done in the main thread, waitone will wait for the result returned by the asynchronous operation to continue the main thread operation. Looking at the second figure, we can see that the asynchronous operation takes only one second, but it is still unscientific to wait three seconds until the main thread method completes and then return the result. Therefore, we need to use the asynchronous Technology of delegate callback.

2. asynchronous callback: Class myclient
{
Private delegate int mydelegate (int A, int B, int time );
Private Static mydelegate md;

[Stathread]
Static void main (string [] ARGs)
{
Datetime dt = datetime. now;
// Remoteobject. myobject APP = (remoteobject. myobject) activator. GetObject (typeof (remoteobject. myobject), system. configuration. configurationsettings. deleettings ["serviceurl"]);
Remoteobject. myobject APP = new remoteobject. myobject ();
MD = new mydelegate (App. alongtimemethod );
Asynccallback AC = new asynccallback (myclient. Callback );
Iasyncresult IAR = md. begininvoke (1000, AC, null );
Method ();
Console. writeline ("used" + (timespan) (datetime. Now-Dt). totalseconds + "second ");
Console. Readline ();
}

Public static void callback (iasyncresult IAR)
{
If (IAR. iscompleted)
{
Console. writeline ("result is" + MD. endinvoke (IAR ));
}
}

Private Static void method ()
{
Console. writeline ("main thread method start ");
System. Threading. thread. Sleep (3000 );
Console. writeline ("main thread method ended ");
}
}

You can see the comment line above, remove the remote call comment, comment on the local call below, compile and start the server, and then start the client to remotely call.

When the asynchronous call ends, the result is displayed immediately. If you enable the remote method, you can see it more clearly:
Client: main thread method start-server: Asynchronous Method end-Client: result 3-Client: main thread method end-client: it took 3.03125 seconds.

3. Unidirectional Asynchronization is used to call a method just like synchronous call methods. The method is completed asynchronously, but the return value of the method cannot be obtained and the exception information of the called method cannot be obtained just like the synchronous method! For a long method that does not need to return information, let's let it do it:

Remote Object:

Using system;
Using system. runtime. remoting. messaging;

Namespace remoteobject
{
Public class myobject: marshalbyrefobject
{
[Oneway]
Public void alongtimemethodoneway (INT time)
{
Console. writeline ("Asynchronous Method start ");
System. Threading. thread. Sleep (time );
Console. writeline ("End of Asynchronous Method ");
}
}
}

[Oneway] attributes are part of remoting. messaging. Do not forget using. Let's look at the client code:

Using system;

Namespace remoteclient
{
Class myclient
{
[Stathread]
Static void main (string [] ARGs)
{
Datetime dt = datetime. now;
Remoteobject. myobject APP = (remoteobject. myobject) activator. GetObject (typeof (remoteobject. myobject), system. configuration. configurationsettings. deleettings ["serviceurl"]);
// Remoteobject. myobject APP = new remoteobject. myobject ();
App. alongtimemethodoneway (1000 );
Method ();
Console. writeline ("used" + (timespan) (datetime. Now-Dt). totalseconds + "second ");
Console. Readline ();
}

Private Static void method ()
{
Console. writeline ("main thread method start ");
System. Threading. thread. Sleep (3000 );
Console. writeline ("main thread method ended ");
}
}
}

This time, we only need to perform remote debugging. We should first make asynchronous methods, and then rest assured that the thread is the main thing.

The running result is described as follows:
Client: main thread method start-server: Asynchronous Method end-Client: main thread method end-Client: 3.8 seconds.

The three methods mentioned above are only part of asynchronous programming. How to call remote methods asynchronously should be combined with the actual example, check whether the return of the method and the running time of the main thread method need to be used in combination with the running time of the remote method. For example, the waithandle mentioned above can also be implemented through polling:
While (IAR. iscompleted = false) system. Threading. thread. Sleep (10); In general, remote object asynchronous operations are very similar to local object asynchronous operations.

You can also refer to msdn articles:
Http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpguide/html/cpconasynchronousprogrammingdesignpattern2.asp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.