asp.net C # asynchronous invocation processing method

Source: Internet
Author: User
Tags sleep

A, with a callback function (Callbackmethod in this case), this callback function is called automatically after the asynchronous end.
B, instead of manually waiting for the asynchronous end in the main thread, as in the last two cases, call EndInvoke in the main thread. In this way, you call the EndInvoke in the callback function.
The approximate process for asynchronous callbacks is this: Start the asynchronous, start the parameter plus the asynchronous end of the method to execute, and then this asynchronous thread does not have to, and finally when the asynchronous thread completes its own work, it automatically executes the startup parameters of the method, it is really very worry, but the code is written, it is very complicated.


One of the simplest asynchronous calls

  code is as follows copy code

Private delegate int asyncfuncdelegate (int m);
Private int Asyncfunc (int m)
{
    for (int i = 0; i < 999999999; i++)
  & nbsp {
        m + = i;
   }
    return m;
}


private void Button1_Click (object sender, EventArgs e)
{
    asyncfuncdelegate afd = Asyncfunc;
    afd. BeginInvoke (1, NULL, NULL);
}
 


For example, to build a delegate for the method to be invoked asynchronously, and then use BeginInvoke to invoke asynchronously, the BeginInvoke argument is followed by the delegate's argument with two more arguments, which we'll talk about here, first null


Method Two

The code is as follows Copy Code
First Ready, asynchronous method (asynchronous, preferably not multiple threads)


Privatestringmethodname (INTNUM,OUTINTNUM2)


{


Num2=num;


return "HelloWorld";


}


Program Endpoint


The method (callback method) that is executed when the asynchronous completes, this method can only have IAsyncResult one parameter, but the parameter is almost omnipotent, can pass object


Privatevoidcallbackmethod (Iasyncresultar)


{


From the asynchronous state ar. AsyncState, get the delegate object


delegatenamedn= (delegatename) ar. asyncstate;


Output parameters


Inti


You must EndInvoke, or you will end up miserable.


Stringr=dn. EndInvoke (Outi,ar);


MessageBox.Show ("Done asynchronously!") The value of I is "i.tostring ()" and the value of R is "R";


}


To define a delegate that has the same signature as a method


Privatedelegatestringdelegatename (INTNUM,OUTINTNUM2);


Program entry


Privatevoidrun ()


{


Instantiating a delegate and assigning it to the initial value


Delegatenamedn=newdelegatename (methodname);


Output parameters


Inti


Instantiating a callback method


Think of AsyncCallback as delegate you know, actually AsyncCallback is a special delegate, like an event.


Asynccallbackacb=newasynccallback (Callbackmethod);


Start asynchronously


If the parameter ACB to NULL means no callback method


The last parameter DN can be replaced with any object that can be retrieved from the parameter by the callback method and written as null. The parameter DN corresponds to the ID of the thread, and if there are more than one asynchronous thread, it can all be null, but absolutely not the same, not the same object, otherwise the exception


Iasyncresultiar=dn. BeginInvoke (1,OUTI,ACB,DN);


To do something else.


............


}


The final result should be: i=1,r= "HelloWorld"


In addition, if you can, you can choose to define the delegate without excessive modification:


&lt;summary&gt;


Defining delegates


&lt;/summary&gt;


&lt;returns&gt;&lt;/returns&gt;


Publicdelegateboolasyncdelegate ();


&lt;summary&gt;


Callbackmethodmusthavethesamesignatureasthe


Asynccallbackdelegate


&lt;/summary&gt;


&lt;paramname= "AR" &gt;&lt;/param&gt;


Privatevoidcallbackmethod (Iasyncresultar)


{


Retrievethedelegate.


asyncdelegatedlgt= (asyncdelegate) ar. asyncstate;


Callendinvoketoretrievetheresults.


Dlgt. EndInvoke (AR);


}


Called in other methods:


Asynchronous execution


Specifying delegate methods


Asyncdelegateisgt=newasyncdelegate (Icpinfo.insert);


Iasyncresultar=isgt. BeginInvoke (Newasynccallback (Callbackmethod), ISGT);

Method Three

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Threading;
Using System.Windows.Forms;

Namespace CW
{


public partial class Asyncdemo:form
{
Public Asyncdemo ()
{
InitializeComponent ();
}

private void Delgate_load (object sender, EventArgs e)
{

}

&lt;summary&gt;


Ways to implement delegates


&lt;/summary&gt;


&lt;param name= "Icalltime" &gt;&lt;/param&gt;


&lt;param name= "Iexecthread" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


String Longrunningmethod (int icalltime, out int iexecthread)


{


Thread.Sleep (Icalltime);


Iexecthread = Appdomain.getcurrentthreadid ();


Return "Mycalltime is" + icalltime.tostring ();


}

Delegate string methoddelegate (int icalltime, out int iexecthread);

        #region Example 1: Synchronous Calling Method #region Example 1: Synchronous calling method
        /**/
       /*
          *  Synchronous Call Methods
         * */
        /**/
       ///<summary>
        ///Example 1: Synchronous call method
       ///</summary>
        public void Demosynccall ()
         {
            string s;
             int iexecthread;

Create an instance of the a delegate that wraps Longrunningmethod.
Methoddelegate dlgt = new Methoddelegate (this. Longrunningmethod);

Call Longrunningmethod using the delegate.
s = DLGT (3000, out iexecthread);

MessageBox.Show (String. Format ("The delegate call returned the string: {0}, and the thread ID {1}", S, Iexecthread.tostring ()));

}
#endregion

#region Example 2: Calling a method asynchronously by EndInvoke ()


/**/


/*


* Using call mode is to invoke BeginInvoke, do some processing of the main thread, and invoke EndInvoke ().


* Note that EndInvoke () does not return until the asynchronous call has completed.


* This call pattern is useful when a calling thread is executing an asynchronous call while working.


* Having concurrent work can improve the performance of many applications.


* Common tasks run asynchronously in this way are file or network operations.


* */


/**/


&lt;summary&gt;


Example 2: Calling a method asynchronously via EndInvoke () call mode


&lt;/summary&gt;


public void Demoendinvoke ()


{


Methoddelegate dlgt = new Methoddelegate (this. Longrunningmethod);


string S;


int iexecthread;

Initiate the asynchronous call.
IAsyncResult ar = dlgt. BeginInvoke (5000, out iexecthread, NULL, NULL);

Do some useful work. This would is work you want to have
Run at the same time as the asynchronous call.

Retrieve the results of the asynchronous call.
s = dlgt. EndInvoke (out Iexecthread, AR);

MessageBox.Show (String. Format ("The delegate call returned the string: {0}, and the number {1}", S, Iexecthread.tostring ()));
}
#endregion

#region Example 3: Calling the method asynchronously and using A WaitHandle to wait for the call to complete


/**/


/*


* Returned by BeginInvoke () IAsyncResult has a AsyncWaitHandle property.


* This property returns WaitHandle after the asynchronous call completes, the notification is. Waiting for WaitHandle is a common thread synchronization technique.


* Through the WaitHandle WaitOne () method calls the thread to wait on the WaitHandle.


* Until notification is WaitHandle WaitOne () block. When WaitOne () returns, you do some extra work before calling EndInvoke ().


* For performing file or network operations, the calling mainline Cheng is blocked, which is useful in previous examples.


* */


/**/


&lt;summary&gt;


Example 3: Calling the method asynchronously and using A WaitHandle to wait for the call to complete


&lt;/summary&gt;


public void Demowaithandle ()


{


string S;


int iexecthread;

Methoddelegate dlgt = new Methoddelegate (this. Longrunningmethod);

Initiate the asynchronous call.
IAsyncResult ar = dlgt. BeginInvoke (3000, out iexecthread, NULL, NULL);

Do some useful work. This would is work you want to have
Run at the same time as the asynchronous call.

Wait for the WaitHandle to become signaled.
Ar. Asyncwaithandle.waitone ();

Get the results of the asynchronous call.
s = dlgt. EndInvoke (out Iexecthread, AR);

MessageBox.Show (String. Format ("The delegate call returned the string: {0}, and the number {1}", S, Iexecthread.tostring ()));
}
#endregion

#region Example 4: Calling a method asynchronously by polling the calling pattern


/**/


/*


* Returned by BeginInvoke () IAsyncResult object has a IsCompleted property returns True after an asynchronous call completes.


* Then you can call EndInvoke (). If your application is constantly working on a long term function call is useful for this calling pattern.


* MicrosoftWindows application is an example of this.


* The primary thread's Windows application can continue to process user input when executing an asynchronous call.


* It can periodically check whether the iscompleted to the call is complete. It calls EndInvoke when IsCompleted returns TRUE.


* until it knows that the operation is complete because EndInvoke () is blocked until the asynchronous operation is complete, the application does not call it.


* */


/**/


&lt;summary&gt;


Example 4: Calling the method asynchronously by polling the call mode


&lt;/summary&gt;


public void demopolling ()


{


Methoddelegate dlgt = new Methoddelegate (this. Longrunningmethod);


string S;


int iexecthread;

Initiate the asynchronous call.
IAsyncResult ar = dlgt. BeginInvoke (3000, out iexecthread, NULL, NULL);

Poll iasyncresult.iscompleted
while (AR. IsCompleted = = False)
{
Thread.Sleep (10); Pretend to so some useful work
}
s = dlgt. EndInvoke (out Iexecthread, AR);

MessageBox.Show (String. Format ("The delegate call returned the string: {0}, and the number {1}", S, Iexecthread.tostring ()));
}
#endregion

#region Example 5: Performing a callback after the asynchronous method completes


/**/


/*


* In this section, the example provides the BeginInvoke () function, in which the system executes the callback delegate after the asynchronous call completes.


* Callback calls EndInvoke () and handles the results of the asynchronous call.


* It is useful to invoke this calling pattern if the asynchronous calling thread is not required to process the result.


* The system call thread is raised after the asynchronous call completes.


* If you use this invocation pattern, the arguments for the second to last-BeginInvoke () function must pass a AsyncCallback type delegate.


* BeginInvoke () also has the last parameter to type the object to you can put any object. When it calls this object can be used for your callback function.


* An important use for this parameter is to pass the delegate for initialization calls.


* The callback function is then used with the delegate EndInvoke () function to complete the call. This invocation pattern is shown in.


* */


/**/


&lt;summary&gt;


Example 5: Performing a callback after the asynchronous method completes


&lt;/summary&gt;


public void Democallback ()


{


Methoddelegate dlgt = new Methoddelegate (this. Longrunningmethod);


int iexecthread;

Create the callback delegate.
AsyncCallback cb = new AsyncCallback (Myasynccallback);

Initiate the asynchronous call passing in the callback delegate
And the delegate object used to initiate the call.
IAsyncResult ar = dlgt. BeginInvoke (5000, out Iexecthread, CB, DLGT);
}

public void Myasynccallback (IAsyncResult ar)
{
string S;
int iexecthread;

Because you passed your original delegate in the AsyncState parameter
Of the Begin call, and you can get it back to complete the call.
Methoddelegate dlgt = (methoddelegate) ar. asyncstate;

Complete the call.
s = dlgt. EndInvoke (out Iexecthread, AR);
MessageBox.Show (String.Format ("The delegate call returned the String: {0}, and the number {1}", S, iexecthread.tostring ()) );

           //console.writeline (string. Format ("The delegate call returned the string:  " {0} ", and the number {1}", S, iexecthread.tostring ());
       }
        #endregion

        private void Button1_Click (object sender, EventArgs e)
         {
           // Demosynccall ();
           //demoendinvoke ();
           //demowaithandle ();
           //demopolling ();
            democallback ();
       }
   }
}

The new thread that comes out asynchronously must be recycled, and not recycled is a shameful act of wasting resources. NET is also not allowed, so you do not want to loopholes, as the saying goes, please God easy to send God difficult, is this truth. Below you can easily think that recycling is divided into 2 kinds of situations: active recovery and passive recycling (of course, this is my own understanding, Microsoft does not say so), active recycling is that you go to monitor the thread, and wait, when the asynchronous method is completed, the asynchronous thread recycling, focus back to the main thread, is actually the last article " C # Asynchronous preliminary in that case, after BeginInvoke and EndInvoke, if in EndInvoke, the asynchronous thread does not complete the operation, then the entire program, including the main thread, and in the blocking, will appear interface "dead" situation. One important way to solve this problem is to use the passive recycle method, which is the "asynchronous callback."

Related Article

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.