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.

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

{<br />

}<br />

onCompletedDelegate = LongTaskCompletion;<br />

public string LongTask(string input)<br />

{<br />

Console.WriteLine("LongTask started");<br />

Thread.Sleep(5000);<br />

Console.WriteLine("LongTask finished");<br />

return input.ToUpper();<br />

}<br />

public void LongTaskAsync(string input, object taskId)<br />

{<br />

//.<br />

}<br />

private void LongTaskCompletion(object operationState)<br />

{<br />

//.<br />

}<br />

protected void OnLongTaskCompleted(LongTaskCompletedEventArgs e)<br />

{<br />

//.<br />

}<br />

// running in a background thread<br />

private void DoLongTask(string input, AsyncOperation asyncOp)<br />

{<br />

//.<br />

}<br />

}<br />

private void CompletionMethod(string output, Exception ex,<br />

bool cancelled, AsyncOperation asyncOp)<br />

{<br />

//.<br />

}<br />

}<br />

public class LongTaskCompletedEventArgs: AsyncCompletedEventArgs<br />

{<br />

//.<br />

}<br />

code snippet AsyncComponent/AsyncComponent.cs<br />

The method LongTaskAsync needs to start the synchronous operation asynchronously. If the component<br />

allows starting the asynchronous task several times concurrently, the client needs to have an option to map<br />

the different results to the tasks started. This is why the second parameter of LongTaskAsync requires a<br />

taskId that can be used by the client to map the results. Of course, inside the component itself the task ID<br />

needs to be remembered to map the results. .<strong>NET</strong> provides the class AsyncOperationManager to create<br />

AsyncOperationObjects to help keep track of the state of operations. The class AsyncOperationManager<br />

has one method, CreateOperation(), where a task identifier can be passed, <strong>and</strong> an AsyncOperation<br />

object is returned. This operation is kept as an item in the dictionary userStateDictionary that was<br />

created earlier.<br />

Then, a delegate of type Action is created, <strong>and</strong> the method DoLongTask is<br />

assigned to that delegate instance. BeginInvoke() is the method of the delegate used to start the method<br />

DoLongTask() asynchronously, using a thread from the thread pool. The parameters needed with this<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!