Asynchronous method invocation: Difference between revisions

Content deleted Content added
Monkbot (talk | contribs)
m Task 16: replaced (9×) / removed (0×) deprecated |dead-url= and |deadurl= with |url-status=;
m Example: 4-space indention
Line 28:
 
<source lang="csharp">
class Example
{
Result Accomplish(args …)
IAsyncResult BeginAccomplish(args …)
Result EndAccomplish(IAsyncResult a)
}</source>
 
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 |accessdate= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archiveurl= https://web.archive.org/web/20081207092841/http://msdn.microsoft.com/en-us/library/ms228963.aspx| archivedate= 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:
 
<source lang="csharp">
interface IAsyncResult
{
bool HasCompleted()
}</source>
 
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 |accessdate= 22 November 2008 |website=.NET Framework Developer's Guide |publisher=Microsoft Developer Network| archiveurl= https://web.archive.org/web/20081223205326/http://msdn.microsoft.com/en-us/library/ms228972.aspx| archivedate= 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 |accessdate=22 November 2008 |website=Distributed Programming with Ice |publisher=ZeroC, Inc. |url-status=dead |archiveurl=https://web.archive.org/web/20080328070322/http://www.zeroc.com/doc/Ice-3.2.1/manual/Async.34.3.html |archivedate=28 March 2008 }}</ref>