Asynchronous in dot net4

15

Click here to load reader

Transcript of Asynchronous in dot net4

Page 1: Asynchronous in dot net4

Asynchronous in DotNet4.5

Page 3: Asynchronous in dot net4

Task & Task<T>

• var t = Task.Factory.StartNew(() => DoAction());• The Task.ContinueWith method and Task<TResult>.ContinueWith

method let you specify a task to be started when the antecedent task finishes.

http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=VS.110).aspx

Page 4: Asynchronous in dot net4

Action<object> action = (object obj) =>{ Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId);};

// Construct an unstarted taskTask t1 = new Task(action, "alpha");// Cosntruct a started taskTask t2 = Task.Factory.StartNew(action, "beta");

// Block the main thread to demonstate that t2 is executingt2.Wait();// Launch t1 t1.Start();

Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId);

// Wait for the task to finish. You may optionally provide a timeout interval or a cancellation token to mitigate situations when the task takes too long to finish.t1.Wait();

// Construct an unstarted taskTask t3 = new Task(action, "gamma");// Run it synchronouslyt3.RunSynchronously();// Although the task was run synchrounously, it is a good practice to wait for it which observes for // exceptions potentially thrown by that task.t3.Wait();

Page 5: Asynchronous in dot net4

async await• The async modifier indicates that the method, lambda expression, or 

anonymous method that it modifies is asynchronous. Such methods are referred to as async methods.

• An async method provides a convenient way to do potentially long-running work without blocking the caller's thread. The caller of an async method can resume its work without waiting for the async method to finish.

• The following example shows the structure of an async method. By convention, async method names end in "Async.“

• Typically, a method modified by the async keyword contains at least one await expression or statement. The method runs synchronously until it reaches the first await expression, at which point it is suspended until the awaited task is complete. In the meantime, control is returned to the caller of the method. If the method does not contain an await expression or statement, then it executes synchronously. A compiler warning alerts you to any async methods that do not contain await.

http://msdn.microsoft.com/en-us/library/hh156513(v=VS.110).aspx

Page 6: Asynchronous in dot net4

public async Task<int> ExampleMethodAsync(){ // . . .

// At the await expression, execution in this method is suspended and, // if AwaitedProcessAsync has not already finished, control returns // to the caller of ExampleMethodAsync. int exampleInt = await AwaitedProcessAsync();

// . . .

// The return statement completes the task. Any method that is // awaiting ExampleMethodAsync can now get the integer result. return exampleInt;}

Page 7: Asynchronous in dot net4

// An event handler must return void.private async void button1_Click(object sender, RoutedEventArgs e){ textBox1.Clear(); // SumPageSizesAsync returns a Task. await SumPageSizesAsync(); textBox1.Text += "\r\nControl returned to button1_Click.\r\n";}

// The following async lambda expression creates an equivalent anonymous// event handler.button1.Click += async (sender, e) => { textBox1.Clear(); // SumPageSizesAsync returns a Task. await SumPageSizesAsync(); textBox1.Text += "\r\nControl returned to button1_Click.\r\n";}

Page 8: Asynchronous in dot net4

// The following async method returns a Task<T>.private async Task<byte[]> GetByteArrayAsync(Uri currentURI){ // Declare an HttpClient object.

HttpClient client = new HttpClient(); // The GetAsync method returns a Task(Of T), where T is an HttpResponseMessage.

Task<HttpResponseMessage> httpRMTask = client.GetAsync(currentURI);

// Await httpRMTask evaluates to an HttpResponseMessage object.

HttpResponseMessage httpRM = await httpRMTask; // The following line can replace the previous two assignment statements. //HttpResponseMessage httpRM = await client.GetAsync(currentURI);

// Throw an exception if the HttpResponseMessage contains an error code.

httpRM.EnsureSuccessStatusCode(); // Use ReadAsByteArray to access the content of the resource as a byte array.

return httpRM.Content.ReadAsByteArray();}

Page 9: Asynchronous in dot net4

Task Parallelism

http://msdn.microsoft.com/en-us/library/dd537609(v=VS.110).aspx

The Task Parallel Library (TPL), as its name implies, is based on the concept of the task. The term task parallelism refers to one or more independent tasks running concurrently. A task represents an asynchronous operation, and in some ways it resembles the creation of a new thread or ThreadPool work item, but at a higher level of abstraction. Tasks provide two primary benefits:

• More efficient and more scalable use of system resources.• Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with

algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.• More programmatic control than is possible with a thread or work item.• Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

For both of these reasons, in the .NET Framework 4, tasks are the preferred API for writing multi-threaded, asynchronous, and parallel code.

Page 10: Asynchronous in dot net4

• The following changes are all that is required to convert from a synchronous to an asynchronous method.

• In the method signature, make the following three changes:– Mark the method with the Async or async modifier.– Change the return value from Byte() or byte[] to Task(Of Byte())

or Task<byte[]>.– By convention, add the suffix "Async" to the method name.

• In the body of the method, make the following two changes:– Change the method that is called from the synchronous Get

method to the asynchronous GetAsync method.– Apply the Await or await operator to the result of the method call.

• That's it. Those few steps complete the conversion.

http://msdn.microsoft.com/en-us/library/hh191443(v=VS.110).aspx

Page 11: Asynchronous in dot net4

Async Samples

• http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html

Page 12: Asynchronous in dot net4

• Performs a series of web requests in sequence using await. The next request will not be issued until the previous request completes.

Page 13: Asynchronous in dot net4

public void AsyncIntroSerialBefore(){ var client = new WebClient();

client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_1; client.DownloadStringAsync(new Uri("http://www.weather.gov"));}

void AsyncIntroSerialBefore_DownloadStringCompleted_1(object sender, DownloadStringCompletedEventArgs e){ WriteLinePageTitle(e.Result);

var client = new WebClient();

client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_2; client.DownloadStringAsync(new Uri("http://www.weather.gov/climate/"));}

void AsyncIntroSerialBefore_DownloadStringCompleted_2(object sender, DownloadStringCompletedEventArgs e){ WriteLinePageTitle(e.Result);

var client = new WebClient();

client.DownloadStringCompleted += AsyncIntroSerialBefore_DownloadStringCompleted_3; client.DownloadStringAsync(new Uri("http://www.weather.gov/rss/"));}

void AsyncIntroSerialBefore_DownloadStringCompleted_3(object sender, DownloadStringCompletedEventArgs e){ WriteLinePageTitle(e.Result);}

C# 4.0

Page 14: Asynchronous in dot net4

public async void AsyncIntroSerial(){ var client = new WebClient();

WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov"))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov/climate/"))); WriteLinePageTitle(await client.DownloadStringTaskAsync(new Uri("http://www.weather.gov/rss/")));}

Async

Page 15: Asynchronous in dot net4

Resources

http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T