15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

event-Based asynchronous Pattern ❘ 539<br />

private void OnWorkCompleted(object sender, RunWorkerCompletedEventArgs e)<br />

{<br />

if (e.Cancelled)<br />

{<br />

this.textBoxResult.Text = "Canceled";<br />

}<br />

else<br />

{<br />

this.textBoxResult.Text = e.Result.ToString();<br />

}<br />

this.buttonCalculate.Enabled = true;<br />

this.buttonCancel.Enabled = false;<br />

this.progressBar.Value = 100;<br />

}<br />

Creating an event-based asynchronous Component<br />

To create a custom component that supports the event-based asynchronous pattern, more work needs to be<br />

done. To demonstrate this with a simple scenario, the class AsyncComponent just returns a converted input<br />

string after a time span, as you can see with the synchronous method LongTask(). To offer asynchronous<br />

support, the public interface provides the asynchronous method LongTaskAsync() <strong>and</strong> the event<br />

LongTaskCompleted. This event is of type EventH<strong>and</strong>ler, which defines<br />

the parameter types object <strong>and</strong> LongTaskCompletedEventArgs. LongTaskCompletedEventArgs is a type<br />

created later where the caller can read the result of the asynchronous operation.<br />

In addition, some helper methods such as DoLongTask <strong>and</strong> CompletionMethod are needed; these are<br />

discussed next.<br />

using System;<br />

using System.Collections.Generic;<br />

using System.ComponentModel;<br />

using System.Threading;<br />

namespace Wrox.ProCSharp.Threading<br />

{<br />

public delegate void LongTaskCompletedEventH<strong>and</strong>ler(object sender,<br />

LongTaskCompletedEventArgs e);<br />

public partial class AsyncComponent: Component<br />

{<br />

private Dictionary userStateDictionary =<br />

new Dictionary();<br />

private SendOrPostCallback onCompletedDelegate;<br />

public event EventH<strong>and</strong>ler LongTaskCompleted;<br />

public AsyncComponent()<br />

{<br />

InitializeComponent();<br />

InitializeDelegates();<br />

}<br />

public AsyncComponent(IContainer container)<br />

{<br />

container.Add(this);<br />

}<br />

InitializeComponent();<br />

InitializeDelegates();<br />

private void InitializeDelegates()<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!