15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

494 ❘ ChaPTer 20 threAds, tAsks, And synchrOnizAtiOn<br />

the result is received with the delegate EndInvoke() method. From the UI st<strong>and</strong>point the result is similar<br />

to the previous sample; just the wait is done in a different manner.<br />

static void Main()<br />

{<br />

TakesAWhileDelegate d1 = TakesAWhile;<br />

}<br />

IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);<br />

while (true)<br />

{<br />

Console.Write(".");<br />

if (ar.AsyncWaitH<strong>and</strong>le.WaitOne(50, false))<br />

{<br />

Console.WriteLine("Can get the result now");<br />

break;<br />

}<br />

}<br />

int result = d1.EndInvoke(ar);<br />

Console.WriteLine("result: {0}", result);<br />

You can read more information about wait h<strong>and</strong>les later in the “ Synchronization ”<br />

section of this chapter.<br />

asynchronous Callback<br />

The third version of waiting for the result from the delegate uses an asynchronous callback. With the third<br />

parameter of BeginInvoke() , you can pass a method that fulfi lls the requirements of the AsyncCallback<br />

delegate. The AsyncCallback delegate defi nes a parameter of IAsnycResult <strong>and</strong> a void return type. Here,<br />

the address of the method TakesAWhileCompleted is assigned to the third parameter, which fulfi lls the<br />

requirements of the AsyncCallback delegate. For the last parameter, you can pass any object for accessing<br />

it from the callback method. It is useful to pass the delegate instance itself, so the callback method can use it<br />

to get the result of the asynchronous method.<br />

The method TakesAWhileCompleted() is invoked as soon as the delegate TakesAWhileDelegate has<br />

completed its work. There is no need to wait for a result inside the main thread. However, you may not end<br />

the main thread before the work of the delegate threads is fi nished, unless you don ’ t have a problem with<br />

delegate threads stopping when the main thread ends.<br />

static void Main()<br />

{<br />

TakesAWhileDelegate d1 = TakesAWhile;<br />

}<br />

d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1);<br />

for (int i = 0; i < 100; i++)<br />

{<br />

Console.Write(".");<br />

Thread.Sleep(50);<br />

}<br />

code snippet Async Delegate/Program.cs<br />

The method TakesAWhileCompleted() is defi ned with the parameter <strong>and</strong> return type specifi ed by the<br />

AsyncCallback delegate. The last parameter passed with the BeginInvoke() method can be read here<br />

by using ar.AsyncState . With the TakesAWhileDelegate , you can invoke the EndInvoke method to get<br />

the result.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!