C # asynchronous programming

Source: Internet
Author: User
Net Framework provides two design modes for asynchronous operations: asynchronous operations using iasyncresult objects and asynchronous operations using events.

Overview The iasyncresult Asynchronous Design Mode implements asynchronous calling of the original synchronous method by calling the beginoperationname and endoperationname methods. For example, the filestream class provides the beginread and endread methods to asynchronously read bytes from files, they are asynchronous versions of the read method.

The begin method includes any parameters in the signature of the synchronous method, and two other parameters: An asynccallback delegate and a user-defined State object. The delegate is used to call the callback method, and the status object is used to pass the status information to the callback method. This method returns an object that implements the iasyncresult interface.

The end method is used to end asynchronous operations and return results. Therefore, it contains the ref and out parameters in the signature of the synchronous method. The return value type is the same as that of the synchronous method. This method also includes an iasyncresult parameter to obtain information about asynchronous operations. Of course, when using this method, you must input the object instance returned by the corresponding begin method.

If the application is blocked after the asynchronous operation is started Program , You can directly call the end method, which will stop the application from executing until the asynchronous operation is complete. You can also use the asyncwaithandle attribute of iasyncresult to call methods such as waitone to block the thread. There is little difference between the two methods, except that the former must keep waiting while the latter can set the wait timeout.

If the application is not blocked, you can use the iscompleted status of iasyncresult to determine whether the operation is completed or use asynccallback to terminate the asynchronous operation. The asynccallback delegate contains an iasyncresult signature, and the callback method calls the end method internally to obtain the operation execution result.


TryFirst, familiarize yourself with today's leading role, iasyncresult Interface

Public interface iasyncresult
{
Object asyncstate {Get ;}
Waithandle asyncwaithandle {Get ;}
Bool completedsynchronously {Get ;}
Bool iscompleted {Get ;}
}




I use an asyncdemo class as the provider of the Asynchronous Method, and subsequent programs will call it. The constructor receives a string as name, and the run method outputs "my name is" + name. The Asynchronous Method directly uses the delegate begininvoke and endinvoke methods.

Public class asyncdemo
{
// Use in asynchronous Methods
Private delegate string rundelegate ();
Private string m_name;
Private rundelegate m_delegate;
Public asyncdemo (string name)
{
M_name = Name;
M_delegate = new rundelegate (run );
}
/**////
/// Synchronous method
///
///
Public String run ()
{
Return "my name is" + m_name;
}
/**////
/// Asynchronous begin Method
///
///
///
///
Public iasyncresult beginrun (asynccallback callback, object stateobject)
{
Try
{
Return m_delegate.begininvoke (callback, stateobject );
}
Catch (exception E)
{
// Hide inside method invoking Stack
Throw E;
}
}
/**////
/// Asynchronous end Method
///
///
///
Public String endrun (iasyncresult AR)
{
If (AR = NULL)
Throw new nullreferenceexception ("arggument ar can't be null ");
Try
{
Return m_delegate.endinvoke (AR );
}
Catch (exception E)
{
// Hide inside method invoking Stack
Throw E;
}
}
}



The first step is to directly call the end method after begin. Of course, other operations can also be performed in the middle.

Class asynctest
{
Static void main (string [] ARGs)
{
Asyncdemo demo = new asyncdemo ("jiangnii ");
// Execute begin Method
Iasyncresult AR = demo. beginrun (null, null );
// You can do other things here
// Use end method to block thread until the operation is complete
String demoname = demo. endrun (AR );
Console. writeline (demoname );
}
}



You can also use the asyncwaithandle attribute of iasyncresult. Here I set it to 1 second timeout.

Class asynctest
{
Static void main (string [] ARGs)
{
Asyncdemo demo = new asyncdemo ("jiangnii ");
// Execute begin Method
Iasyncresult AR = demo. beginrun (null, null );
// You can do other things here
// Use asyncwaithandle. waitone method to block thread for 1 second at most
Ar. asyncwaithandle. waitone (1000, false );
If (AR. iscompleted)
{
// Still need use end method to get result,
// But this time it will return immediately
String demoname = demo. endrun (AR );
Console. writeline (demoname );
}
Else
{
Console. writeline ("Sorry, can't get demoname, the time is over ");
}
}
}



A non-interrupted round robin outputs "."

Class asynctest
{
Static void main (string [] ARGs)
{
Asyncdemo demo = new asyncdemo ("jiangnii ");
// Execute begin Method
Iasyncresult AR = demo. beginrun (null, null );
Console. Write ("waiting ..");
While (! Ar. iscompleted)
{
Console. Write (".");
// You can do other things here
}
Console. writeline ();
// Still need use end method to get result,
// But this time it will return immediately
String demoname = demo. endrun (AR );
Console. writeline (demoname );
}
}



The last step is to use the callback method and add a State object. The State object is passed to the callback method as the asyncstate attribute of the iasyncresult parameter. The main thread cannot be exited before the callback method is executed. Here I just put it down for 1 second. Another difference is that the asyncdemo object is defined as a static field of the class for the callback method to use.

Class asynctest
{
Static asyncdemo demo = new asyncdemo ("jiangnii ");
Static void main (string [] ARGs)
{
// State object
Bool state = false;
// Execute begin Method
Iasyncresult AR = demo. beginrun (New asynccallback (output), State );
// You can do other thins here
// Wait until callback finished
System. Threading. thread. Sleep (1000 );
}
// Callback Method
Static void output (iasyncresult AR)
{
Bool state = (bool) Ar. asyncstate;
String demoname = demo. endrun (AR );
If (state)
{
Console. writeline (demoname );
}
Else
{
Console. writeline (demoname + ", isn' t it? ");
}
}
}


OthersFor an object that has implemented the beginoperationname and endoperationname methods, we can call them directly in the preceding method, but for objects that only have the synchronous method, we do not need to add the corresponding Asynchronous Method for its asynchronous call. Instead, we only need to define a delegate and use its begininvoke and endinvoke methods.

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.