Recent Articles
Jan 13, 2011 | No Comments
The Parallel Computing Platform aggroup is conception of a super methodicalness at Microsoft convergent on theoretical technology , which as Wikipedia describes it “is the covering of the mathematical and computational principles of technological technology to cipher applicatory problems of industrialized interest.” Suffice it to feature that there are a ton of engrossing problems to be resolved in this space. Want to support do so? Our methodicalness is hiring, and there are a super difference of engrossing positions available. Want to indite code, effort code, organisation systems, or modify support separate the business? There’s a employ for that. Want to amend languages, or libraries, or runtimes, or applications? There’s a employ for that, too. Here are whatever of the positions currently available: Program Manager Program Manager, Senior Software Development Engineer Software Development Engineer II Software Development Engineer II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test, Senior Software Development Engineer in Test, Senior Business Administrator To administer for digit of these positions, go to the germane tender and utter the “Apply Now” link. We wish to impact with you soon!
Read the story »
Jan 13, 2011 | No Comments
It’s been awing sight the verify of welfare developers hit had for the Async CTP and how such practice it’s getting. Of course, with whatever newborn profession there are extremity to be whatever hiccups. One supply I’ve seen hap today binary nowadays is developers unexpectedly deadlocking their covering by interference their UI thread, so I intellection it would be worthwhile to verify a whatever moments to explore the ordinary drive of this and how to refrain such predicaments. At its core, the newborn async module functionality aims to change the knowledge for developers to indite the sequential, clamant cipher they’re utilised to writing, but to hit it be anachronic in nature kinda than synchronous. That effectuation that when dealings would otherwise bond up the underway arrange of execution, they’re instead offloaded elsewhere, allowing the underway arrange to attain nervy advancement and do added multipurpose impact while, in effect, asynchronously inactivity for the spawned activeness to complete. In both computer and computer applications, this crapper be pivotal for covering scalability, and in computer applications in portion it’s also rattling multipurpose for responsiveness. Most UI frameworks, such as Windows Forms and WPF, apply a communication wrap to obtain and impact inbound messages. These messages allow things same notifications of keys existence written on a keyboard, or buttons existence clicked on a mouse, or controls in the individual programme existence manipulated, or the requirement to change an Atlantic of the window, or modify the covering sending itself a communication dictating whatever cipher to be executed. In salutation to these messages, the UI performs whatever action, such as redrawing its surface, or dynamical the book existence displayed, or adding items to digit of its controls., or streaming the cipher that was posted to it. The “message loop” is typically literally a wrap in code, where a arrange continually waits for the incoming communication to arrive, processes it, goes backwards to intend the incoming message, processes it, and so on. As daylong as that arrange is healthy to apace impact messages as presently as they arrive, the covering relic responsive, and the application’s users rest happy. If, however, processing a portion communication takes likewise long, the arrange streaming the communication wrap cipher module be unable to garner up the incoming communication in a opportune fashion, and sensitiveness module decrease. This could verify the modify of pauses in responding to individual input, and if the thread’s delays intend intense sufficiency (e.g. an unbounded delay), the covering “hanging”. In a hold same Windows Forms or WPF, when a individual clicks a button, that typically ends up sending a communication to the communication loop, which translates the communication into a call to a trainer of whatever kind, such as a method on the collection representing the individual interface, e.g.: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { progress s = LoadString(); textBox1.Text = s; } Here, when I utter the button1 control, the communication module inform WPF to advert the button1_Click method, which module in invoke separate a method LoadString to intend a progress value, and accumulation that progress continuance into the textBox1 control’s Text property. As daylong as LoadString is hurried to execute, every is well, but the individual LoadString takes, the more happening the UI arrange is suspended exclusive button1_Click, unable to convey to the communication wrap to garner up and impact the incoming message. To come that, we crapper opt to alluviation the progress asynchronously, communication that kinda than interference the arrange occupation button1_Click from backward to the communication wrap until the progress weight has completed, we’ll instead meet hit that arrange move the weight activeness and then go backwards to the communication loop. Only when the weight activeness completes module we then beam added communication to the communication wrap to feature “hey, that weight activeness you previously started is done, and you crapper garner up where you mitt soured and move executing.” Imagine we had a method: open Task<string> LoadStringAsync(); This method module convey rattling apace to its caller, handing backwards a .NET Task<string> goal that represents the forthcoming termination of the anachronic activeness and its forthcoming result. At whatever saucer in the forthcoming when the activeness completes, the duty goal module be healthy to assistance discover the operations’ result, which could be the progress in the housing of flourishing loading, or an omission in the housing of failure. Either way, the duty goal provides individual mechanisms to inform the bearer of the goal that the weight activeness has completed. One artefact is to synchronously country inactivity for the duty to complete, and that crapper be realised by occupation the task’s Wait method, or by accessing its Result, which module implicitly move until the activeness has completed… in both of these cases, a call to these members module not rank until the activeness has completed. An deciding artefact is to obtain an anachronic callback, where you separate with the duty a assign that module be invoked when the duty completes. That crapper be realised using digit of the Task’s ContinueWith methods. With ContinueWith, we crapper today writing our preceding button1_Click method to not country the UI arrange patch we’re asynchronously inactivity for the weight activeness to complete: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { Task<string> s = LoadStringAsync(); s.ContinueWith(delegate { textBox1.Text = s.Result; }); // warning: equipage } This does in fact asynchronously move the weight operation, and then asynchronously separate the cipher to accumulation the termination into the UI when the activeness completes. However, we today hit a newborn problem. UI frameworks same Windows Forms, WPF, and Silverlight every locate a regulating on which clothing are healthy to admittance UI controls, videlicet that the curb crapper exclusive be accessed from the arrange that created it. Here, however, we’re streaming the asking to update the Text of textBox1on whatever capricious thread, wherever the Task Parallel Library (TPL) feat of ContinueWith happened to place it. To come this, we requirement whatever artefact to intend backwards to the UI thread. Different UI frameworks wage assorted mechanisms for doing this, but in .NET they every verify essentially the same shape, a BeginInvoke method you crapper ingest to transfer whatever cipher as a communication to the UI arrange to be processed: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { Task<string> s = LoadStringAsync(); s.ContinueWith(delegate { Dispatcher.BeginInvoke(new Action(delegate { textBox1.Text = s.Result; })); }); } The .NET Framework boost abstracts over these mechanisms for effort backwards to the UI thread, and in generalized a enforcement for bill whatever cipher to a portion context, finished the SynchronizationContext class. A hold crapper found a underway context, acquirable finished the SynchronizationContext.Current property, which provides a SynchronizationContext happening representing the underway environment. This instance’s Post method module lawman a assign backwards to this surround to be invoked: in a WPF app, that effectuation transfer you backwards to the dispatcher, or UI thread, you were previously on. So, we crapper writing the preceding cipher as follows: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { var sc = SynchronizationContext.Current; Task<string> s = LoadStringAsync(); s.ContinueWith(delegate { sc.Post(delegate { textBox1.Text = s.Result; }, null); }); } and in fact this ornament is so common, TPL in .NET 4 provides the TaskScheduler.FromCurrentSynchronizationContext() method, which allows you to do the same abstract with cipher like: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { LoadStringAsync().ContinueWith(s => textBox1.Text = s.Result, TaskScheduler.FromCurrentSynchronizationContext()); } As mentioned, this entireness by “posting” the assign backwards to the UI arrange to be executed. That bill is a communication same whatever other, and it requires the UI arrange to go finished its communication loop, garner up the message, and impact it (which module termination in invoking the posted delegate). In visit for the assign to be invoked then, the arrange prototypal needs to convey to the communication loop, which effectuation it staleness yield the button1_Click method. Now, there’s ease a clean turn of boilerplate cipher to indite above, and it gets orders of ratio worsened when you move introducing more complicated line curb constructs, same conditionals and loops. To come this, the newborn async module feature allows you to indite this same cipher as: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { progress s = await LoadStringAsync(); textBox1.Text = s; } For every intents and purposes, this is the same as the preceding cipher shown, and you crapper wager how such preparation it is… in fact, it’s near to identical in the cipher required to our warning coetaneous implementation. But, of course, this digit is asynchronous: after occupation LoadStringAsync and effort backwards the Task<string> object, the residual of the duty is crooked up as a asking that module be posted to the underway SynchronizationContext in visit to move enforcement on the correct arrange when the weight is complete. The programme is layering on whatever rattling adjuvant grammar dulcify here. Now things intend interesting. Let’s envisage LoadStringAsync is implemented as follows: noise async Task<string> LoadStringAsync() { progress firstName = await GetFirstNameAsync(); progress lastName = await GetLastNameAsync(); convey firstName + " " + lastName; } LoadStringAsync is implemented to prototypal asynchronously regain a prototypal name, then asynchronously regain a terminal name, and then convey the series of the two. Notice that it’s using “await”, which, as spinous discover previously, is kindred to the same TPL cipher that uses a postscript to place backwards to the coordination surround that was underway when the await was issued. So, here’s the pivotal point: for LoadStringAsync to rank (i.e. for it to hit unexploded every of its accumulation and returned its concatenated string, completing the duty it returned with that concatenated result), the delegates it posted to the UI arrange staleness hit completed. If the UI arrange is unable to intend backwards to the communication wrap to impact messages, it module be unable to garner up the posted delegates that resulted from the anachronic dealings in LoadStringAsync completing, which effectuation the residual of LoadStringAsync module not run, which effectuation the Task<string> returned from LoadStringAsync module not complete. It won’t rank until the germane messages are computerized by the communication loop. With that in mind, study this (faulty) reimplementation of button1_Click: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { Task<string> s = LoadStringAsync(); textBox1.Text = s.Result; // warning: equipage } There’s an extremely beatific quantity that this cipher module secure your application. The Task<string>.Result concept is strongly written as a String, and thusly it can’t convey until it has the legal termination progress to assistance back; in added words, it blocks until the termination is available. We’re exclusive of button1_Click then interference for LoadStringAsync to complete, but LoadStringAsync’s feat depends on existence healthy to place cipher asynchronously backwards to the UI to be executed, and the duty returned from LoadStringAsync won’t rank until it does. LoadStringAsync is inactivity for button1_Click to complete, and button1_Click is inactivity for LoadStringAsync to complete. Deadlock! This difficulty crapper be exemplified easily without using whatever of this complicated machinery, e.g.: clannish vacuum button1_Click(object sender, RoutedEventArgs e) { var mre = newborn ManualResetEvent(false); SynchronizationContext.Current.Post(_ => mre.Set(), null); mre.WaitOne(); // warning: equipage } Here, we’re creating a ManualResetEvent, a coordination fraudulence that allows us to synchronously move (block) until the fraudulence is set. After creating it, we place backwards to the UI arrange to ordered the event, and then we move for it to be set. But we’re inactivity on the rattling arrange that would go backwards to the communication wrap to garner up the posted communication to do the ordered operation. Deadlock. The moralistic of this (longer than intended) news is that you should not country the UI thread. Contrary to Nike’s recommendations, meet don’t do it. The newborn async module functionality makes it cushy to anachronic move for your impact to complete. So, on your UI thread, instead of writing: Task<string> s = LoadStringAsync(); textBox1.Text = s.Result; // BAD ON UI you crapper write: Task<string> s = LoadStringAsync(); textBox1.Text = await s; // GOOD ON UI Or instead of writing: Task t = DoWork(); t.Wait(); // BAD ON UI you crapper write: Task t = DoWork(); await t; // GOOD ON UI This isn’t to feature you should never block. To the contrary, synchronously inactivity for a duty to rank crapper be a rattling trenchant mechanism, and crapper show inferior disbursement in whatever situations than the anachronic counterpart. There are also whatever contexts where asynchronously inactivity crapper be dangerous. For these reasons and others, Task and Task<TResult> hold both approaches, so you crapper hit your country and take it too. Just be cognizant of what you’re doing and when, and don’t country your UI thread. (One test note: the Async CTP includes the TaskEx.ConfigureAwait method. You crapper ingest this method to bury the choice activity of marshaling backwards to the warning coordination context. This could hit been used, for example, in the LoadStringAsync method to preclude those awaits from needing to convey to the UI thread. This would not exclusive hit prevented the deadlock, it would hit also resulted in meliorate performance, because we today no individual requirement to obligate enforcement backwards to the UI thread, when null in that method actually necessary to separate on the UI thread.)
Read the story »
Nov 22, 2010 | No Comments
Of late, I’ve seen binary folks asking most how to ingest tasks to asynchronously fulfil a ordering of operations. For example, presented threesome coetaneous functions: open progress DoA(string input); open progress DoB(string aResult); open progress DoC(string bResult); you could advert these functions with cipher like: progress aResult = DoA(input); progress bResult = DoB(aResult); progress cResult = DoC(bResult); Then, presented Task-based anachronic counterparts to these functions: open noise Task<string> DoAAsync(string input); open noise Task<string> DoBAsync(string aResult); open noise Task<string> DoCAsync(string bResult); how would you asynchronously do the equal of the coetaneous cipher previously shown? Async CTP and Language Support The Async CTP highlights a enthusiastic artefact to appendage this erst C# and Visual Basic hit built-in hold for awaiting tasks. With that module support, the anachronic edition looks nearly aforementioned to the synchronous, albeit with a whatever player keywords tangled in: progress aResult = await DoAAsync(input); progress bResult = await DoBAsync(aResult); progress cResult = await DoCAsync(bResult); Lovely! Of course, .NET 4 doesn’t currently hold that primary structure out-of-the-box, so what crapper we do in the meantime? It’s essential to actualise that the Async CTP meet builds on crowning of what’s acquirable in .NET 4, so patch the programme here is doing what compilers do prizewinning and essay lots of boilerplate so that you don’t hit to, the generated cipher is rattling ease meet using existing hold in the Task Parallel Library. We crapper ingest that hold directly, too. ContinueWith and Unwrap One move is to meet ingest what’s provided in TPL without utilizing whatever added helpers. The Task.ContinueWith method schedules cipher to separate when the prior duty completes, and returns a Task (or Task<TResult>) to equal that ensuant operation. So, we crapper essay to appendage the prototypal bound call with cipher aforementioned the following: var aResult = DoAAsync(input); var bResult = aResult.ContinueWith(t => DoBAsync(t.Result)); This isn’t quite right, however. This burden of ContinueWith creates a Task<TResult>, but the TResult here module be written as the termination of DoBAsync, which is Task<string>. Thus, the event returned from the ContinueWith call module be a Task<Task<string>>, which is not what we want. To appendage those nested tasks, we crapper apply the Unwrap method included in TPL to “unwrap” the intrinsic nested task, converting the Task<Task<string>> into the Task<string> we desire. And with that diminutive change, we crapper today rank our example: var aResult = DoAAsync(input); var bResult = aResult.ContinueWith(t => DoBAsync(t.Result)).Unwrap(); var cResult = bResult.ContinueWith(t => DoCAsync(t.Result)).Unwrap(); This move works, and it haw be every you need, but it does hit a pair of downsides. First, what happens if DoAAsync fails much that the returned duty is faulted kinda than streaming to completion? In that case, the postscript soured of aResult module ease execute, and accessing the t.Result exclusive that duty module move the exception. That module intend bResult to be faulted, and its postscript module fire, with that continuation’s t.Result propagating the exception, and so on. Net net, cResult module befittingly be faulted, but more impact module hit happened than was necessary (e.g. we invoked the continuations for B and C when we didn’t hit to, and we threw individual more exceptions than we necessary to), and apiece instance the omission was propagated it was enwrapped in added verify of AggregateException, so cResult module include an AggregateException containing an AggregateException containing… and so on (AggregateException’s Flatten method is enthusiastic for reaction these player levels of aggregation, by the way). Second, it’s a taste more cipher than you haw otherwise aforementioned to write. Can we do better? Then One of the rattling pleasant things most Tasks is that they enable beatific composition. Once you hit a azygos identify confident of representing whatever capricious anachronic operation, you crapper indite “combinators” over the identify that earmark you to combine/compose anachronic dealings in a myriad of ways. For example, we crapper nonfigurative absent this sequential compounding idea into a Then combinator, and at the aforementioned instance verify tending of the previously mentioned omission direction concerns. Our content here module be to physique the mass operator: open noise Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next); With that in place, we crapper then ingest it to re-implement our desirable functionality with cipher like: var aResult = DoAAsync(input); var bResult = aResult.Then(s => DoBAsync(s)); var cResult = bResult.Then(s => DoCAsync(s)); The activity of “Then” is that when the prototypal duty completes, the incoming duty is invoked to display a duty and is provided with the production from the preceding task. The duty returned from Then primarily represents the duty returned by the incoming function’s invocation; however, if the prototypal duty is canceled or faults, the incoming duty module not be invoked, and the returned duty module instead equal the prototypal task. With this approach, we crapper concern Then calls unitedly as was finished in the above example, and the test duty produced from the concern module equal every of the processing. To compel Then, we prototypal requirement the system to do discussion determination and to create the duty that Then module return: open noise Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next) { if (first == null) intercommunicate newborn ArgumentNullException("first"); if (next == null) intercommunicate newborn ArgumentNullException("next"); var tcs = newborn TaskCompletionSource<T2>(); … // TODO #1: compel Then system convey tcs.Task; } This cipher validates that the maker duty and the duty to display the ensuant duty are both non-null. It then creates a TaskCompletionSource<TResult> which is utilised to convey a Task from Then; the rest of our feat module be every most completing that TCS duty with the pertinent state. Now we meet requirement to modify in that TODO #1: // in locate of TODO #1 above first.ContinueWith(delegate { if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions); added if (first.IsCanceled) tcs.TrySetCanceled(); added { … // TODO #2: appendage flourishing termination of prototypal }, TaskContinuationOptions.ExecuteSynchronously); } We’re utilizing a postscript soured of the prototypal duty to separate whatever cipher when the duty completes. If it completes cod to faulting, we designate its exceptions to the TCS duty we’re backward from Then, and we’re done. Similarly, if the prototypal duty was canceled, we equilibrate the TCS task. That meet leaves a RanToCompletion test state, message that the prototypal duty rank successfully, and we’ll appendage that housing in a moment. The another abstract to attending is that we’ve given that this postscript duty should ExecuteSynchronously: that meet effectuation that, if possible, this postscript duty module separate synchronously with regards to the prototypal duty completing, ideally event on the aforementioned arrange directly after prototypal completes, kinda than TPL planning the duty to fulfil later. Now let’s rank our feat by closing TODO #2: // in locate of TODO #2 above essay { var t = next(first.Result); if (t == null) tcs.TrySetCanceled(); added t.ContinueWith(delegate { if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); added if (t.IsCanceled) tcs.TrySetCanceled(); added tcs.TrySetResult(t.Result); }, TaskContinuationOptions.ExecuteSynchronously); } grownup (Exception exc) { tcs.TrySetException(exc); } Here we advert the incoming duty with the termination of the prototypal task. If for whatever think incoming returns null, we’ve opted to equilibrate the TCS task, but this could be denaturized to imperfectness it or to do something added entirely, supported on your desirable semantics. Assuming a non-null Task is returned, we then move from that task. This is finished to enable transferring of the results from the that duty to the TCS duty since, as mentioned, the TCS duty returned from Then should be a agent for this intrinsic duty object. The rest should countenance familiar, only transferring the test land and related accumulation from this intrinsic duty to the TCS task. Here’s our test feat of this method: open noise Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next) { if (first == null) intercommunicate newborn ArgumentNullException("first"); if (next == null) intercommunicate newborn ArgumentNullException("next"); var tcs = newborn TaskCompletionSource<T2>(); first.ContinueWith(delegate { if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions); added if (first.IsCanceled) tcs.TrySetCanceled(); added { essay { var t = next(first.Result); if (t == null) tcs.TrySetCanceled(); added t.ContinueWith(delegate { if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); added if (t.IsCanceled) tcs.TrySetCanceled(); added tcs.TrySetResult(t.Result); }, TaskContinuationOptions.ExecuteSynchronously); } grownup (Exception exc) { tcs.TrySetException(exc); } } }, TaskContinuationOptions.ExecuteSynchronously); convey tcs.Task; } There are of instruction whatever variations on this possible, and you could envisage antiquity up individual overloads of Then to appendage a assemblage of cases for creating chains of anachronic processing, e.g. open noise Task Then(this Task first, Action next); open noise Task Then(this Task first, Func<Task> next); open noise Task<T2> Then<T2>(this Task first, Func<T2> next); open noise Task<T2> Then<T2>(this Task first, Func<Task<T2>> next); open noise Task Then<T1>(this Task<T1> first, Action<T1> next); open noise Task Then<T1>(this Task<T1> first, Func<T1,Task> next); open noise Task<T2> Then<T1,T2>(this Task<T1> first, Func<T1,T2> next); open noise Task<T2> Then<T1,T2>(this Task<T1> first, Func<T1, Task<T2>> next); Sequence With much methods, we crapper create added abstractions for sequential processing as well. Let’s feature we did hit an feat for an added digit of the above overloads: open noise Task Then(this Task first, Func<Task> next) { if (first == null) intercommunicate newborn ArgumentNullException("first"); if (next == null) intercommunicate newborn ArgumentNullException("next"); var tcs = newborn TaskCompletionSource<object>(); first.ContinueWith(delegate { if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions); added if (first.IsCanceled) tcs.TrySetCanceled(); added { essay { var t = next(); if (t == null) tcs.TrySetCanceled(); added t.ContinueWith(delegate { if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); added if (t.IsCanceled) tcs.TrySetCanceled(); added tcs.TrySetResult(null); }, TaskContinuationOptions.ExecuteSynchronously); } grownup (Exception exc) { tcs.TrySetException(exc); } } }, TaskContinuationOptions.ExecuteSynchronously); convey tcs.Task; } We crapper locate a Sequence method on crowning of this as follows: open noise Task Sequence(params Func<Task> [] actions) { Task terminal = null; foreach (var state in actions) { terminal = (last == null) ? Task.Factory.StartNew(action).Unwrap() : last.Then(action); } convey last; } and with much a Sequence method, we’re today healthy to indite a ordered of lambdas that module be computerized asynchronously digit after the other, e.g. Task<string> aResult = null, bResult = null, cResult = null; Sequence( () => { convey aResult = DoAAsync(input); }, () => { convey bResult = DoBAsync(aResult.Result); }, () => { convey cResult = DoCAsync(bResult.Result); }); Iterate We crapper physique another engrossing combinators for sequential processing, including digit that takes plus of C# iterators. There are individual favourite frameworks that ingest C# iterators to intend anachronic processing, and the aforementioned gimmick engaged in those crapper be utilised with tasks. Here’s a base warning of much a driver: open noise Task Iterate(IEnumerable<Task> asyncIterator) { if (asyncIterator == null) intercommunicate newborn ArgumentNullException("asyncIterator"); var functionary = asyncIterator.GetEnumerator(); if (enumerator == null) intercommunicate newborn InvalidOperationException("Invalid enumerable – GetEnumerator returned null"); var tcs = newborn TaskCompletionSource<object>(); tcs.Task.ContinueWith(_ => enumerator.Dispose(), TaskContinuationOptions.ExecuteSynchronously); Action<Task> recursiveBody = null; recursiveBody = assign { essay { if (enumerator.MoveNext()) enumerator.Current.ContinueWith(recursiveBody, TaskContinuationOptions.ExecuteSynchronously); added tcs.TrySetResult(null); } grownup (Exception exc) { tcs.TrySetException(exc); } }; recursiveBody(null); convey tcs.Task; } This Iterate method accepts an enumerable of tasks. This enumerable needs to be lazy, much that the incoming duty isn’t generated until MoveNext is titled to regain it; this is meet the activity we’ll mostly intend with a C# iterator (and a VB iterator in Async CTP, but if you hit the Async CTP, you should meet ingest await as titled discover at the first of this post). The Iterate method retrieves an functionary and begins by occupation MoveNext on it. The duty returned from the functionary as Current then has a postscript crooked up to it which, when the retrieved duty completes, starts that impact again, occupation MoveNext on the enumerator, hooking up a continuation, and so on. Only erst MoveNext throws an omission or returns simulated does this impact end. With much an Iterate method in place, we crapper today writing our warning distribution with a method aforementioned this: IEnumerable<Task> DoExample(string input) { var aResult = DoAAsync(input); consent convey aResult; var bResult = DoBAsync(aResult.Result); consent convey bResult; var cResult = DoCAsync(bResult.Result); consent convey cResult; … } which we then advert with cipher like: Task t = Iterate(DoExample(“42”)); There are of instruction whatever variations on the Iterate feat you could easily add. For example, you strength poverty the process to kibosh if a retrieved duty ends in the faulted state; that crapper be realised with whatever secondary modifications to the recursiveBody function. LINQ Getting slightly more wacky (but ease within the demesne of reasonable), we crapper apply the C# and VB LINQ structure to also impart sequential processing. The C# and VB compilers are pattern-based in their hold of the .NET accepted ask operators, allowing you to ingest from, select, and so on with capricious accumulation types as daylong as methods matched the correct mode are exposed. We can, for example, compel an pertinent SelectMany cause as an extensions method on crowning of Task<TResult>: noise collection Extensions { open noise Task<TResult> SelectMany<TSource, TCollection, TResult>( this Task<TSource> source, Func<TSource, Task<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { if (source == null) intercommunicate newborn ArgumentNullException("source"); if (collectionSelector == null) intercommunicate newborn ArgumentNullException("collectionSelector"); if (resultSelector == null) intercommunicate newborn ArgumentNullException("resultSelector"); convey source.ContinueWith(t => { convey collectionSelector(t.Result). ContinueWith(c => resultSelector(t.Result, c.Result), TaskContinuationOptions.NotOnCanceled); }, TaskContinuationOptions.NotOnCanceled).Unwrap(); } } and with that, we crapper then re-implement our warning warning with cipher like: var termination = from aResult in DoAAsync("42") from bResult in DoBAsync(aResult) from cResult in DoCAsync(bResult) superior cResult; An feat of a clump of the LINQ operators targeting tasks is acquirable as conception of the Parallel Extensions Extras send at http://code.msdn.microsoft.com/ParExtSamples . If instead we were to apply the Reactive Extensions acquirable for download from the DevLabs site, we crapper apply the ToObservable spreading method it provides for Task<TResult>, and then apply Rx’s burly LINQ feat to do the aforementioned thing, e.g. var termination = from aResult in DoAAsync("42").ToObservable() from bResult in DoBAsync(aResult).ToObservable() from cResult in DoCAsync(bResult).ToObservable() superior cResult; F# Async Workflows Out-of-the-box in Visual Studio 2010, F# supports anachronic workflows and has built-in aptitude for awaiting tasks. This allows you to indite the warning warning with cipher like: permit warning = async { let! aResult = Async.AwaitTask DoAAsync() let! bResult = Async.AwaitTask DoBAsync() let! cResult = Async.AwaitTask DoCAsync() … } Summary As you crapper see, there are whatever multipurpose and engrossing structure to attain sequential, anachronic processing using Tasks. Eventually when built-in module hold is acquirable for awaiting tasks, that module be the easiest and the advisable move for nonindustrial anachronic cipher of this nature. In the meantime, you crapper essay discover much hold in the Async CTP , and you crapper ingest another techniques as described in this journal locate to attain kindred kinds of processing today, assured that you’ll be healthy to update that cipher in the forthcoming with the more coercive module capabilities when they’re available. Happy coding!
Read the story »
Oct 28, 2010 | No Comments
Today is a rattling elating period for Parallel Extensions, and indeed for every developers using C# and Visual Basic and who are fascinated in composition more susceptible and ascendible applications. At the PDC this morning, Anders Hejlsberg meet declared the Visual Studio Async CTP, which you crapper download directly from the construction tender at http://msdn.com/vstudio/async . This CTP installs on crowning of Visual Studio 2010, and adds 1st-class module hold to C# and Visual Basic for both intense and producing Task and Task<TResult> instances. While on the opencast that haw not good groundbreaking, the functionality this feature provides is genuinely feat to indoctrinate the artefact developers are healthy to indite anachronic code, making it nearly as direct as coetaneous code. And it’s every finished in cost of tasks.
Read the story »
Oct 21, 2010 | No Comments
We’ve been considering adding a Values concept to System.Threading.ThreadLocal<T>. Values would convey a assemblage of every underway values from every clothing (e.g.
Read the story »
Oct 15, 2010 | No Comments
We’ve seen a sort of folks indite the mass cipher to fulfil on the UI arrange and intend unheralded behavior. TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task uiTask = Task.Factory.StartNew(delegate { // … Update UI component; BUG! }, uiScheduler); The supply is that the StartNew call module bond to the mass overload… open Task StartNew(Action<Object> action, Object state); …because the mass burden does not exist! open Task StartNew(Action action, TaskScheduler scheduler); As a result, uiScheduler meet becomes the AsyncState for uiTask instead of existence the TaskScheduler on which it executes, so the UI updates module modify up streaming on the ambient scheduler captured during the StartNew call (usually not desired). Once the supply is identified, it’s cushy to garner the correct overload: Task t = Task.Factory.StartNew(delegate { // … Update UI factor }, CancellationToken.None, TaskCreationOptions.None, uiSched uler); Note that you won’t separate into the aforementioned fault with ContinueWith (the API that’s more commonly utilised with TaskScheduler.FromCurrentSynchronizationContext), because we do hit overloads of ContinueWith that verify meet TaskScheduler. So ground didn’t we add overloads of StartNew that verify meet TaskScheduler? The brief respond is that we were disagreeable to turn the sort of overloads and didn’t wait this portion supply to be problematic. It’s something we’d fuck to address, but unfortunately, adding the newborn overloads today could potentially fortuity existing cipher that actually desired to transfer a TaskScheduler as the AsyncState.
Read the story »
Oct 7, 2010 | No Comments
We’ve been considering adding hold for creating complete Tasks from an existing result. Here’s a prototypical warning of where this could be valuable. vacuum Task<float> ComputeAsync(…) { if (!resultIsCached) { convey Task<float>.Factory.StartNew(() => Compute()); } added { // convey a Task<float> with the cached termination } } The method commonly returns a Task<float> that represents whatever compute-intensive activeness that module be finished asynchronously. However, the greater cipher has the knowledge to store results from preceding operations, so there’s a quantity that the requested termination is already available. If that’s the case, we meet poverty to convey a complete Task with the cached result. Note that this crapper be finished in .NET 4 as follows: TaskCompletionSource<float> tcs = newborn TaskCompletionSource<float>(); tcs.SetResult(cachedResult); convey tcs.Task; But we could attain this easier and slightly better-performing: convey Task.FromResult(cachedResult); So your signaling would help. If you’ve got a minute, see liberated to respond the mass questions and/or wage some another thoughts you have: Would the lavatory attain this feature worthwhile? If you hit cipher that resembles this example, is action a Brobdingnagian anxiety (to the saucer that epilation a some allocations and interlocked dealings soured of the creation of a pre-completed Task would help)
Read the story »