Asynchronous method invocation: Difference between revisions
m r2.6.5) (robot Adding: zh:异步方法调用 |
GreenC bot (talk | contribs) Rescued 1 archive link. Wayback Medic 2.5 |
||
(46 intermediate revisions by 33 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Software design pattern}} |
|||
⚫ | |||
In [[Thread (computer science)|multithreaded]] [[computer programming]], '''asynchronous method invocation''' ('''AMI'''), also known as '''asynchronous method calls''' or the '''asynchronous pattern''' is a [[software design pattern|design pattern]] in which the call site is not [[Blocking (computing)|blocked]] while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives. Polling for a reply is an undesired option. |
|||
⚫ | It is equivalent to the |
||
⚫ | |||
== Background == |
|||
⚫ | In most programming languages a called method is executed synchronously, i.e. in the [[thread (computer science)|thread of execution]] from which it is invoked. If the method |
||
⚫ | '''AMI''' is a [[software design pattern|design pattern]] for [[asynchrony (computer programming)|asynchronous]] invocation of potentially long-running [[method (computer science)|methods]] of an [[object (computer science)|object]].<ref name="Async.34.2#71139">{{cite web|url=http://www.zeroc.com/doc/Ice-3.2.1/manual/Async.34.2.html#71139 |title=Asynchronous Method Invocation |access-date=22 November 2008 |website=Distributed Programming with Ice |publisher=ZeroC, Inc. |url-status=dead |archive-url=https://web.archive.org/web/20080105093534/http://www.zeroc.com/doc/Ice-3.2.1/manual/Async.34.2.html |archive-date=5 January 2008 }}</ref> |
||
⚫ | It is equivalent to the IOU ("I owe you") pattern described in 1996 by Allan Vermeulen.<ref>{{cite journal |last=Vermeulen |first=Allan |date=June 1996 |title=An Asynchronous Design Pattern |journal=[[Dr. Dobb's Journal]] |url=http://www.ddj.com/184409898 |access-date=22 November 2008 }}</ref><ref>{{cite book |last=Nash |first=Trey |title=Accelerated C# 2008 | year=2007 |publisher=Apress |isbn=978-1-59059-873-3 |chapter=Threading in C# }}</ref> |
||
⚫ | In most programming languages a called method is executed synchronously, i.e. in the [[thread (computer science)|thread of execution]] from which it is invoked. If the method takes a long time to complete, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time. |
||
⚫ | |||
| title=Active Object | url=http://www.cs.wustl.edu/~schmidt/PDF/Act-Obj.pdf | format=PDF |
|||
⚫ | One common use of AMI is in the [[active object]] design pattern. Alternatives are synchronous method invocation and [[futures and promises|future objects]].<ref name="active object">{{cite journal | last=Lavender | first=R. Greg | author2=Douglas C. Schmidt | title=Active Object | url=http://www.cs.wustl.edu/~schmidt/PDF/Act-Obj.pdf | access-date=22 November 2008 | archive-url=https://web.archive.org/web/20120722180050/http://www.cs.wustl.edu/%7Eschmidt/PDF/Act-Obj.pdf | archive-date=2012-07-22 | url-status=dead | author2-link=Douglas C. Schmidt }}</ref> |
||
| accessdate=22 November 2008 }}</ref> |
|||
An example for an application that may make use of AMI is a web browser that needs to display a web page even before all images are loaded. |
An example for an application that may make use of AMI is a web browser that needs to display a web page even before all images are loaded. |
||
Since [[method (computer science)|method]] is a special case of [[Procedure_(computer_science)|procedure]], '''asynchronous method invocation''' is a special case of [[asynchronous procedure call]]. |
|||
⚫ | |||
== Implementations == |
|||
⚫ | The following example is loosely based on a standard AMI style used in the [[.NET Framework]].<ref name="ms228969">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228969.aspx |title=Asynchronous Programming Design Patterns | |
||
=== Java class === |
|||
⚫ | FutureTask class<ref>{{cite web|title=Class FutureTask |url=https://docs.oracle.com/javase/6/docs/enwiki/api/java/util/concurrent/FutureTask.html |archive-url=http://webarchive.loc.gov/all/20130625215130/http://docs.oracle.com/javase/6/docs/enwiki/api/java/util/concurrent/FutureTask.html |url-status=dead |archive-date=2013-06-25 |publisher=Oracle |date=2011 |access-date=2015-06-29 }}</ref> in [[Java (programming language)|Java]] use [[event (synchronization primitive)|events]] to solve the same problem. This pattern is a variant of AMI whose implementation carries more overhead, but it is useful for objects representing [[Component-based software engineering|software components]]. |
||
=== .NET Framework === |
|||
* Asynchronous Programming Model (APM) pattern (used before .NET Framework 2.0)<ref>{{cite web|title=Asynchronous Programming Model|url=https://msdn.microsoft.com/en-us/library/ms228963(v=vs.110).aspx|publisher=Microsoft|date=2015|access-date=2015-06-29}}</ref> |
|||
* Event-based Asynchronous Pattern (EAP) (used in .NET Framework 2.0)<ref>{{cite web| title=Event-based Asynchronous Pattern Overview|url = https://msdn.microsoft.com/en-us/library/wewwczdw(v=vs.110).aspx|publisher=Microsoft|date=2015|access-date=2015-06-29}}</ref> |
|||
* Task-based Asynchronous Pattern (TAP) (used in .NET Framework 4.0)<ref>{{cite web|title=Task-based Asynchronous Pattern|url=https://msdn.microsoft.com/en-us/library/hh873175(v=vs.110).aspx|publisher=Microsoft|date=2015|access-date=2015-06-29}}</ref> |
|||
⚫ | |||
⚫ | The following example is loosely based on a standard AMI style used in the [[.NET Framework]].<ref name="ms228969">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228969.aspx |title=Asynchronous Programming Design Patterns |access-date=22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archive-url= https://web.archive.org/web/20081122091746/http://msdn.microsoft.com/en-us/library/ms228969.aspx| archive-date= 22 November 2008 | url-status= live}}</ref> |
||
Given a method <code>Accomplish</code>, one adds two new methods <code>BeginAccomplish</code> and <code>EndAccomplish</code>: |
Given a method <code>Accomplish</code>, one adds two new methods <code>BeginAccomplish</code> and <code>EndAccomplish</code>: |
||
<syntaxhighlight lang="csharp"> |
|||
<code> |
|||
class Example |
|||
{ |
|||
Result Accomplish(args …) |
|||
Result Accomplish(args …) |
|||
IAsyncResult BeginAccomplish(args …) |
|||
Result EndAccomplish(IAsyncResult a) |
Result EndAccomplish(IAsyncResult a) |
||
… |
… |
||
}</code> |
|||
}</syntaxhighlight> |
|||
Upon calling <code>BeginAccomplish</code>, the client immediately receives an object of type <code>AsyncResult</code> (which implements the <code>IAsyncResult</code> interface), so it can continue the calling thread with unrelated work. In the simplest case, eventually there is no more such work, and the client calls <code>EndAccomplish</code> (passing the previously received object), which blocks until the method has completed and the result is available.<ref name="ms228963">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228963.aspx |title=Asynchronous Programming Overview | |
Upon calling <code>BeginAccomplish</code>, the client immediately receives an object of type <code>AsyncResult</code> (which implements the <code>IAsyncResult</code> interface), so it can continue the calling thread with unrelated work. In the simplest case, eventually there is no more such work, and the client calls <code>EndAccomplish</code> (passing the previously received object), which blocks until the method has completed and the result is available.<ref name="ms228963">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228963.aspx |title=Asynchronous Programming Overview |access-date= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archive-url= https://web.archive.org/web/20081207092841/http://msdn.microsoft.com/en-us/library/ms228963.aspx| archive-date= 7 December 2008 | url-status= live}}</ref> The <code>AsyncResult</code> object normally provides at least a method that allows the client to query whether the long-running method has already completed: |
||
<syntaxhighlight lang="csharp"> |
|||
<code> |
|||
interface IAsyncResult |
|||
{ |
|||
bool HasCompleted() |
bool HasCompleted() |
||
… |
… |
||
}</code> |
|||
}</syntaxhighlight> |
|||
One can also pass a callback method to <code>BeginAccomplish</code>, to be invoked when the long-running method completes. It typically calls <code>EndAccomplish</code> to obtain the return value of the long-running method. A problem with the callback mechanism is that the callback function is naturally executed in the worker thread (rather than in the original calling thread), which may cause race conditions.<ref name="ms228972">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228972.aspx |title=Using an AsyncCallback Delegate to End an Asynchronous Operation | |
One can also pass a callback method to <code>BeginAccomplish</code>, to be invoked when the long-running method completes. It typically calls <code>EndAccomplish</code> to obtain the return value of the long-running method. A problem with the callback mechanism is that the callback function is naturally executed in the worker thread (rather than in the original calling thread), which may cause race conditions.<ref name="ms228972">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228972.aspx |title=Using an AsyncCallback Delegate to End an Asynchronous Operation |access-date= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archive-url= https://web.archive.org/web/20081223205326/http://msdn.microsoft.com/en-us/library/ms228972.aspx| archive-date= 23 December 2008 | url-status= live}}</ref><ref name="Async.34.3#76161">{{cite web|url=http://www.zeroc.com/doc/Ice-3.2.1/manual/Async.34.3.html#76161 |title=Concurrency Issues |access-date=22 November 2008 |website=Distributed Programming with Ice |publisher=ZeroC, Inc. |url-status=dead |archive-url=https://web.archive.org/web/20080328070322/http://www.zeroc.com/doc/Ice-3.2.1/manual/Async.34.3.html |archive-date=28 March 2008 }}</ref> |
||
In the .NET Framework documentation, the term event-based asynchronous pattern refers to an alternative API style (available since .NET 2.0) using a method named <code>AccomplishAsync</code> instead of <code>BeginAccomplish</code>.<ref name=nageletal>{{cite book|title=Professional C# 2008| |
In the .NET Framework documentation, the term event-based asynchronous pattern refers to an alternative API style (available since .NET 2.0) using a method named <code>AccomplishAsync</code> instead of <code>BeginAccomplish</code>.<ref name=nageletal>{{cite book|title=Professional C# 2008|url=https://archive.org/details/professionalcsha2008nage|url-access=limited|author1=Christian Nagel |author2=Bill Evjen |author3=Jay Glynn |author4=Karli Watson |author5=Morgan Skinner |name-list-style=amp |pages=[https://archive.org/details/professionalcsha2008nage/page/n630 570]–571|publisher=Wiley|year=2008|isbn=9780470191378|chapter=Event-based Asynchronous Pattern}}</ref><ref name="hkasytyf">{{cite web |url=http://msdn.microsoft.com/en-us/library/hkasytyf.aspx |title=Multithreaded Programming with the Event-based Asynchronous Pattern |access-date= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archive-url= https://web.archive.org/web/20081225175311/http://msdn.microsoft.com/en-us/library/hkasytyf.aspx| archive-date= 25 December 2008 | url-status= live}}</ref> |
||
A superficial difference is that in this style the return value of the long-running method is passed directly to the callback method. Much more importantly, the API uses a special mechanism to run the callback method (which resides in an event object of type <code>AccomplishCompleted</code>) in the same thread in which <code>BeginAccomplish</code> was called. This eliminates the danger of race conditions, making the API easier to use and suitable for software components; on the other hand this implementation of the pattern comes with additional object creation and synchronization overhead.<ref name="ms228966">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228966.aspx |title=Deciding When to Implement the Event-based Asynchronous Pattern | |
A superficial difference is that in this style the return value of the long-running method is passed directly to the callback method. Much more importantly, the API uses a special mechanism to run the callback method (which resides in an event object of type <code>AccomplishCompleted</code>) in the same thread in which <code>BeginAccomplish</code> was called. This eliminates the danger of race conditions, making the API easier to use and suitable for software components; on the other hand this implementation of the pattern comes with additional object creation and synchronization overhead.<ref name="ms228966">{{cite web |url=http://msdn.microsoft.com/en-us/library/ms228966.aspx |title=Deciding When to Implement the Event-based Asynchronous Pattern |access-date= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archive-url= https://web.archive.org/web/20081122092048/http://msdn.microsoft.com/en-us/library/ms228966.aspx| archive-date= 22 November 2008 | url-status= live}}</ref> |
||
==References== |
==References== |
||
Line 40: | Line 55: | ||
== Further reading == |
== Further reading == |
||
* {{cite book|title=Programming WPF| |
* {{cite book|title=Programming WPF|url=https://archive.org/details/programmingwpfbu00sell|url-access=limited|author1=Chris Sells |author2=Ian Griffiths |name-list-style=amp |chapter=Appendix C.3: The Event-Based Asynchronous Pattern|pages=[https://archive.org/details/programmingwpfbu00sell/page/n773 747]–749|publisher=O'Reilly|year=2007|isbn=9780596510374}} |
||
* [http://articles.techrepublic.com.com/5100-10878_11-1044325.html Using asynchronous method calls in C#] |
* [http://articles.techrepublic.com.com/5100-10878_11-1044325.html Using asynchronous method calls in C#] |
||
{{Design Patterns patterns}} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
[[zh:异步方法调用]] |
|||
⚫ |
Latest revision as of 01:52, 10 June 2022
In multithreaded computer programming, asynchronous method invocation (AMI), also known as asynchronous method calls or the asynchronous pattern is a design pattern in which the call site is not blocked while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives. Polling for a reply is an undesired option.
Background
[edit]AMI is a design pattern for asynchronous invocation of potentially long-running methods of an object.[1] It is equivalent to the IOU ("I owe you") pattern described in 1996 by Allan Vermeulen.[2][3]
In most programming languages a called method is executed synchronously, i.e. in the thread of execution from which it is invoked. If the method takes a long time to complete, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time.
One common use of AMI is in the active object design pattern. Alternatives are synchronous method invocation and future objects.[4] An example for an application that may make use of AMI is a web browser that needs to display a web page even before all images are loaded.
Since method is a special case of procedure, asynchronous method invocation is a special case of asynchronous procedure call.
Implementations
[edit]Java class
[edit]FutureTask class[5] in Java use events to solve the same problem. This pattern is a variant of AMI whose implementation carries more overhead, but it is useful for objects representing software components.
.NET Framework
[edit]- Asynchronous Programming Model (APM) pattern (used before .NET Framework 2.0)[6]
- Event-based Asynchronous Pattern (EAP) (used in .NET Framework 2.0)[7]
- Task-based Asynchronous Pattern (TAP) (used in .NET Framework 4.0)[8]
Example
[edit]The following example is loosely based on a standard AMI style used in the .NET Framework.[9]
Given a method Accomplish
, one adds two new methods BeginAccomplish
and EndAccomplish
:
class Example
{
Result Accomplish(args …)
IAsyncResult BeginAccomplish(args …)
Result EndAccomplish(IAsyncResult a)
…
}
Upon calling BeginAccomplish
, the client immediately receives an object of type AsyncResult
(which implements the IAsyncResult
interface), so it can continue the calling thread with unrelated work. In the simplest case, eventually there is no more such work, and the client calls EndAccomplish
(passing the previously received object), which blocks until the method has completed and the result is available.[10] The AsyncResult
object normally provides at least a method that allows the client to query whether the long-running method has already completed:
interface IAsyncResult
{
bool HasCompleted()
…
}
One can also pass a callback method to BeginAccomplish
, to be invoked when the long-running method completes. It typically calls EndAccomplish
to obtain the return value of the long-running method. A problem with the callback mechanism is that the callback function is naturally executed in the worker thread (rather than in the original calling thread), which may cause race conditions.[11][12]
In the .NET Framework documentation, the term event-based asynchronous pattern refers to an alternative API style (available since .NET 2.0) using a method named AccomplishAsync
instead of BeginAccomplish
.[13][14]
A superficial difference is that in this style the return value of the long-running method is passed directly to the callback method. Much more importantly, the API uses a special mechanism to run the callback method (which resides in an event object of type AccomplishCompleted
) in the same thread in which BeginAccomplish
was called. This eliminates the danger of race conditions, making the API easier to use and suitable for software components; on the other hand this implementation of the pattern comes with additional object creation and synchronization overhead.[15]
References
[edit]- ^ "Asynchronous Method Invocation". Distributed Programming with Ice. ZeroC, Inc. Archived from the original on 5 January 2008. Retrieved 22 November 2008.
- ^ Vermeulen, Allan (June 1996). "An Asynchronous Design Pattern". Dr. Dobb's Journal. Retrieved 22 November 2008.
- ^ Nash, Trey (2007). "Threading in C#". Accelerated C# 2008. Apress. ISBN 978-1-59059-873-3.
- ^ Lavender, R. Greg; Douglas C. Schmidt. "Active Object" (PDF). Archived from the original (PDF) on 2012-07-22. Retrieved 22 November 2008.
{{cite journal}}
: Cite journal requires|journal=
(help) - ^ "Class FutureTask". Oracle. 2011. Archived from the original on 2013-06-25. Retrieved 2015-06-29.
- ^ "Asynchronous Programming Model". Microsoft. 2015. Retrieved 2015-06-29.
- ^ "Event-based Asynchronous Pattern Overview". Microsoft. 2015. Retrieved 2015-06-29.
- ^ "Task-based Asynchronous Pattern". Microsoft. 2015. Retrieved 2015-06-29.
- ^ "Asynchronous Programming Design Patterns". .NET Framework Developer's Guide. Microsoft Developer Network. Archived from the original on 22 November 2008. Retrieved 22 November 2008.
- ^ "Asynchronous Programming Overview". .NET Framework Developer's Guide. Microsoft Developer Network. Archived from the original on 7 December 2008. Retrieved 22 November 2008.
- ^ "Using an AsyncCallback Delegate to End an Asynchronous Operation". .NET Framework Developer's Guide. Microsoft Developer Network. Archived from the original on 23 December 2008. Retrieved 22 November 2008.
- ^ "Concurrency Issues". Distributed Programming with Ice. ZeroC, Inc. Archived from the original on 28 March 2008. Retrieved 22 November 2008.
- ^ Christian Nagel; Bill Evjen; Jay Glynn; Karli Watson & Morgan Skinner (2008). "Event-based Asynchronous Pattern". Professional C# 2008. Wiley. pp. 570–571. ISBN 9780470191378.
- ^ "Multithreaded Programming with the Event-based Asynchronous Pattern". .NET Framework Developer's Guide. Microsoft Developer Network. Archived from the original on 25 December 2008. Retrieved 22 November 2008.
- ^ "Deciding When to Implement the Event-based Asynchronous Pattern". .NET Framework Developer's Guide. Microsoft Developer Network. Archived from the original on 22 November 2008. Retrieved 22 November 2008.
Further reading
[edit]- Chris Sells & Ian Griffiths (2007). "Appendix C.3: The Event-Based Asynchronous Pattern". Programming WPF. O'Reilly. pp. 747–749. ISBN 9780596510374.
- Using asynchronous method calls in C#